Javascript - Basics

Javascript is a dynamically typed language, which means we don't need to specify types (just like Python). But there are some technologies which can turn JS into static typing, like supersets of JS and add-ons (Typescript, Flow).

Use console

// log to console
console.log('Hello world');
console.log(123);
console.log(true);
console.log([1,2,3]);
console.log({a: 1, b: 2});
// log a table to console
console.table({a: 1, b: 2});]

console.error("This is an error");
console.warn("This is aa warning");
// clear all the logs in console
console.clear()
// calculate the time of some program
console.time('hello');
...some program
console.timeEnd('hello');

/* multi-line comments
...
*/


Variables

Variable names only consist of letters, numbers, _, $. The money sign is only used in case of Jquery. _ is used for private variable. They cannot start with number.

definition and declaration of variables

  • var (old)
  • let (commonly used now)
  • const (variable cannot be reassigned)
var name = "just for test";
//declare var
var greetings;
// multi word vars, use camel case
var firstName;

// let, usage is the same as var
let name = "just for test";

console.log(name);

// const, constant which can not be redefine or reassigned
// it must be initialized with a certain value
const name = "John";
console.log(name);

//but things in the const variable dict can be changed
const dict = {
    name: "John",
    age: 30
}

dict.name = "haha"; // use key name
console.log(dict);

const array = [1, 2, 3, 4];
array.push(5);
console.log(array);

// don't use const in a iterator or loop which redefine a variable many times
// otherwise, just use const


Primitive Data Types vs Reference Types

primitive data types:

  • String
  • Number
  • Boolean
  • Null
  • Undefined
  • Symbols(ES6)
// String
const name = "John";
console.log(typeof name);

const car = null;
console.log(typeof car); // it return an object, it is actually a bug of JS, it should be a primitive data type

const sym = Symbol();
console.log(sym);

reference types:

  • array
  • object literals (just dictionary in python)
  • functions
  • dates
  • anything else...(when use console.log, all reference types return "object")
const today = new Date(); // give the a time to the argument to set time, e.g. '01-20-2012 11:25:00' or use '/' instead of '-'

val = today.getMonth(); // return the month number minus 1
val = today.getDate(); // return the day
val = today.getDay(); // return the number of the day in a week starting from Sunday
val = today.getFullYear();
val = today.getHours();
val = today.getMinutes();
val = today.getSeconds();
val = today.getMilliseconds();
val = today.getTime(); // get timestamp

// set time
today.setMonth(2);
today.setDate(12);
today.setFullYear(1995);
today.setHours(2);
today.setMinutes(20);
today.setSeconds(20);

console.log(today);
console.log(typeof today);


Type Conversion

let val;
// number to string
val = String(5);
// boolean to string
val = String(true);
// date to string
val = String(new Date());
// array to string
val = String([1,2,3,4]);
// toString() method
val = (true).toString();

console.log(val);
console.log(typeof val);
console.log(val.length); // length property is only used for string

// string to number
val = Number('5');
val = Number(true); // it is converted to 1, and 0 for both false and null
val = Number("hello"); // give a Nan (not a number)
val = Number([1,2,3]); // also give a Nan (not a number)

//parse to get a integer number
val = parseInt('100')
//float
val = parseFloat('100.31')

console.log(val);
console.log(typeof val);
console.log(val.toFixed()); // toFixed() set the number of decimals, the number is its argument. no argument no decimal.

If you add one string and a number, you get a string. This is called type coercion (Coercion is the term that is used for unexpected type casting in JavaScript). It is also operator overloading in other programming languages. You can also use + to add two strings which is similar to Python


The Math Object

val = Math.PI; // Math is an object, PI is its property
val = Math.E
val = Math.round(2.8); // 3
val = Math.ceil(2.4); // 3
val = Math.floor(2.8); // 2
val = Math.sqrt(64); // 8
val = Math.abs(-3); // 3
val = Math.pow(8, 2); // 64
val = Math.min(2, 33, 14); // 2
val = Math.max(2, 33, 14); // 33
val = Math.random(); 0 - 1


Strings

let val;

val = "John";
val = val.concat(' ', "Brad");

val = val.toUpperCase();
val = val.toLowerCase();
console.log(val);

part1 = val[2]; // use index to get a character of a string
part2 = val.charAt(2); // it is the same
console.log(part1, part2);

index1 = val.indexOf('h'); // return 2
index2 = val.lastIndexOf('h'); // return 6, search from the last character, but the index is counted from the beginning
console.log(index1, index2);

//substring
part3 = val.substring(0, 4);
//slicing
part4 = val.slice(0, 4);
part5 = val.slice(-3); // start from the back and take the last three
//split
tokens = val.split(' ');
console.log(tokens);
//replace 
val = val.replace('brad', 'Jack');
console.log(val);
//include
included = val.includes('Jack');
console.log(included);


Template Literals

ES5 way

const name = 'John';
const age = 30;

html = '<ul>' + 
    '<li>Name: ' + name + '</li>' + 
    '<li>Age: ' + age + '</li>' + 
    '</ul>';

document.body.innerHTML = html; 

ES6 way

function hello() {
    return 'hello';
}
html = `
     <ul>
        <li>Name: ${name}</li>
        <li>Age: ${age}</li>
        <li>${hello()}</li>
        <li>${age > 20? 'Yes' : 'No'}</li>
    </ul>
`
document.body.innerHTML = html;


Arrays $ Array Methods

// create array
const numbers = [1,2,3,4];
const numbers1 = new Array(1,2,3,4); // it's the same
const mixed = [22, 'hello', true, undefined, null, {a: 1, b: 2}, new Date()]; // different from Java whose array can only contain elements with the same type

// get array length
val = numbers.length;
// check if it is a array
val = Array.isArray(numbers);
// get a single value using index
val = numbers[3];
// find index of value
val = numbers.indexOf(2);

// mutating arrays
// add on to end
numbers.push(110);
// add on to front
numbers.unshift(120);
// take off from end
numbers.pop();
// take off from front
numbers.shift();
// splice values
numbers.splice(1,3) // namely cut off the part between indexes of 1 and 3 (inclusive)
// reverse an array
numbers.reverse();

// concatenate array
val = numbers.concat(numbers1); 
// sort
val = numbers.sort();// sort by the first number, then the second and so forth

// sort from the lowest to the highest by using a compare function
val = numbers.sort(function(x, y){
    return x - y; // use y - x to sort from the highest to lowest
});

// find and return the first element that satisfy the condition
numbers.find(function(x){
    return x < 3;
})


Object literals (Dictionaries)

The usage is just similar to Python. One special thing is you can add a function into an object.

let val;
let val1;

const person = {
    name: "John",
    getBirthYear: function() {
        return 2001;
    },
    getAge: function() {
        return 2018 - this.getBirthYear(); // this is the object itself
    }
}

val = person.getBirthYear();
val1 = person.getAge();

console.log(val, val1);


If & For & While & Switch

If

Curly braces can be omitted like Java but not suggested.

const id = '100';

if(id == 100) {
    console.log('CORRECT');
} else {
    console.log('INCORRECT');
}

Note: '100' == 100 is also true in the if statement which is different from Python. So it's better to use three equal signs, which ensures that the type is also equal.

if(id === 100) {
    console.log('CORRECT');
} else if(id > 101 && id < 200) { // AND &&, OR ||
    console.log('GRAY ZONE');
} else {
    console.log('INCORRECT');
}

// not equal !==, test if some variable undefined
if(typeof id1 !== 'undefined') { // Note: here don't use if(id) to check if it is existing.
    console.log('The ID is ${id}'); //template literal
} else {
    console.log('No ID');
}

// ternary operator
console.log(id === 100 ? 'CORRECT' : 'INCORRECT');


Switch

const color = 'red';

switch(color){
    case 'red':
        console.log('Color is red');
        break;
    case 'blue':
        console.log('Color is blue');
        break;
    default:
        console.log('Neither red nor blue');
        break;
}


For

The usage of for loop is basically the same as Java's. The continue and break can also be used in the same way.

forEach() loop is worth mentioning.

const cars = ['Ford', 'Chevy', 'Honda', 'Toyota'];
cars.forEach(function(car, index, array){ // these arguments are you choice, it is not necessary
    console.log('${index} : ${car}');
    console.log(array); // return the entire array, i.e. cars
});

For in loop

const user = {
    firstName: "John",
    lastName: "Doe",
    age: 40
}

for (let x in user){
    console.log('${x} : ${user[x]}');
}

Map

const users = [
    {id: 1, name: 'John'},
    {id: 2, name: 'Sara'},
    {id: 3, name: 'Karen'},
    {id: 4, name: 'Steve'}
];

const ids = users.map(function(user){
    return user.id;
});

console.log(ids); // return an array of the ids


while

The usage of while loop is basically the same as Java's. The continue and break can also be used in the same way.

Do while

let i = 100;
do {
    console.log(i);
    i++;
}
while(i < 10);


Functions

1.In JS, function expression can be assigned to a variable

const square = function(x = 3){
    return x*x;
};
console.log(square());

2.Immediately invokable function expression, a.k.a IIFEs

(function(name){
    console.log("IIFE Ran... " + name);
})('Brad');

3.Object methods are as shown above in "Object literals" section.


Window Object and Its Methods and Properties

console and alert are both parts of window object.

// similar to alert, prompt is also popped up when you open the webpage. But it is a form which you need to fill in.
const input = prompt(); // pop up a form
alert(input); // after you fill in and enter, the message shows an alert

// confirm is often used when you are deleting something to make sure it is not by accident.
if(confirm('Are you sure')){
    console.log('YES');
}

let val;

// outer height and width of the window (browser)
val = window.outerHeight;
val = window.outerWidth;

// Inner height and width (not including scroll bar, navigator, etc)
val = window.innerHeight;
val = window.innerWidth;

// Scroll points, i.e. where is the scroll bar in the window
// used for animations when you scroll down, when to show the animations
val = window.scrollY;
val = window.scrollX;

// Location Object
val = window.location;
val = window.location.hostname;
val = window.location.port;
val = window.location.href;
val = window.location.search; // the query after the href, e.g. ?id=1

// Redirect
window.location.href = "http://google.com";
//Reload
window.location.reload(); // just keep on refreshing the webpage 
// History 
window.history.go(-2); // get to the page before the last one
val = window.history.length;
// Navigator Object
val = window.navigator;
val = window.navigator.appName;
val = window.navigator.appVersion;
val = window.navigator.userAgent;
val = window.navigator.platform; // show user's platform like Mac, Windows
val = window.navigator.vendor;
val = window.navigator.language; // language of the browser

console.log(val);


Scope

The scope of JS is similar to other languages like Python, Java. But one thing needs attention:

The variable defined by var in a block scope({}, for, if, etc) can change the value of the variable with the same name in the global scope. So that's why let and const are more common to be used.

类似文章推荐

    暂无类似文章!

登录注册后参与评论