Variable
use let
or var
Tips:
- Cannot be a reserved keyword, such as if else…
- Should be meaningful,try using meaning words
- Cannot start with a number, eg 1name
- Cannot contain a space or hyphen (-),
- eg
let firstName
, this is called Camel notation - Are case-sensitive
Constants
const interestRate = 0.3;
Primitive Types/Value Types
- String:
let name = 'Daniel';
- Number:
let age = 33;
- Boolean:
let isApproved = false;
- undefined:
let firstname = undefined;
, this is a type also is a value - null:
let selectedColor = null;
Dynamic Typing
- 主要意思是变量的类型可以变化,看赋值情况
- JavaScript dont have two kinds of numbers floating-point numbers and integers 只有一种类型叫做number
Reference Types
Object
let person = {
name: 'Daniel',
age: 30
};
// Dot Notation
person.name = 'Huang';
//Bracket Notation
person['name'] = 'DanielHuang
//Bracket Notaion (real life)
let selection = 'name';
person[selection] = 'DanielHuang';
console.log(perso.name);
List
//initialize an empty array
//let selectedColors = [];
let selectedColors = ['red', 'blue', 'green']
//Aboaut index, selectedColors[0] whichi is red
//the length is dynamic, also the type of objects, for example['red', 'blue', 888]
console.log(selectedColors[0]);
console.log(selectedColors.length);
//length in here is a property.
Functions
Function declaration: A statement or variable we need to terminated with a semicolon(;), but function dont need.
Daniel here now er refer to this as an argument so Daniel is an argument pass the greet function.
Parameter is at that time of declaration but the argument is the actual value with supply for that parameter.
//Performing a task
//function has parameter, eg name
function greet(name){
console.log('hello ' + name);
}
greet('Daniel'); //argument
Type of Function
//Calculating a value
function square(number){
return number * number;
}
let number = square(2);
console.log(number);
Example: Dog Years Calculator
const myAge = 8;
let earlyYears = 2;
earlyYears *= 10.5;
let lastYears = myAge - 2;
lastYears *= 4;
console.log(earlyYears,lastYears);
let myAgeInDogYears = earlyYears + lastYears;
//way to call a string’s built-in method
let myName = ('Butter').toLowerCase();
//way 1 string concatenation
console.log("My name is " + myName + "." + "I am " + myAge + " years old in human years which is " + myAgeInDogYears + " years old in dog years.");
//way 2 String interpolation is when we insert, or interpolate, variables into strings using template literals.
console.log(`My name is ${myName}. I am ${myAgeInDogYears} years old in dog years.`);