CONDITIONAL STATEMENTS

if

let sale = true
if(sale){
  console.log('Time to buy!')
}

If...Else

let sale = true
sale = false
if(sale) {
  console.log('Time to buy!')
}
else{
  console.log('Time to wait for a sale.')
}

Comparison Operators

let hungerLevel = 7
if(hungerLevel>7){
  console.log('Time to eat!')
}
else{
  console.log('We can eat later!')
}

Logical Operators

  • theandoperator (&&)
  • theoroperator (||)
  • the notoperator, otherwise known as the_bang_operator (!)
let mood = 'sleepy';
let tirednessLevel = 6;

if((mood === 'sleepy') &&(tirednessLevel >8)){
  console.log('time to sleep')
}
else{
  console.log('not bed time yet')
}

Truthy and Falsy

考虑non-boolean data types

表示错误的有

  • 0
  • Empty strings like "" or'' 空字符串
  • nullwhich represent when there is no value at all
  • undefinedwhich represent when a declared variable lacks a value 未定义变量
  • NaN, or Not a Number

Truthy and Falsy Assignment

||or statements check the left-hand condition first

所以这两个是等价的

let  defaultName
if  (username)  { 
defaultName  =  username
} 
else  {
defaultName  =  'Stranger'
}
let  defaultName  =  username  ||  'Stranger';
let tool = 'marker';
let writingUtensil = tool ||'pen'
console.log(`The ${writingUtensil} is mightier than the  sword.`);
The pen is mightier than the sword.
let tool = '';
let writingUtensil = tool ||'pen'
console.log(`The ${writingUtensil} is mightier than the sword.`);
The marker is mightier than the sword.

Ternary Operator

三元运算符

isNightTime  ?  console.log('Turn on the lights!')  :  console.log('Turn off the lights!');
  • 条件在?前面
  • ?后面有两个待执行语句,用:隔开
  • 如果条件为真,执行第一个语句(:前面的),为假执行第二个(:后面的)

Else If Statements

let stopLight = 'yellow'
if (stopLight === 'red'){ 
console.log('Stop!')
} 
else if (stopLight === 'yellow'){ 
console.log('Slow down.')
} 
else if (stopLight === 'green'){
console.log('Go!'); 
}  
else{  
console.log('Caution, unknown!')
}

The switch keyword

let athleteFinalPosition = 'first place';

switch(athleteFinalPosition){
       case (athleteFinalPosition === 'first place'):
       console.log('You get the gold medal!')
       break
    case (athleteFinalPosition === 'second place'):
       console.log('You get the silver medal!')
       break
    case (athleteFinalPosition === 'third place'):
       console.log('You get the bronze medal!')
       break
    default:
    console.log('No medal awarded.')
    break
       }

function

Function Declarations

function getReminder(){
  console.log('Water the plants.')
}
function greetInSpanish(){
  console.log('Buenas Tardes.')
}

Calling a Function

function sayThanks(){
  console.log('Thank you for your purchase! We appreciate your business.')
}
sayThanks()

Parameters and Arguments



function sayThanks(name) {
  console.log("Thank you for your purchase "+name+"! We appreciate your business.");
}
sayThanks('Cole')

Default Parameters

Default parameters allow parameters to have a predetermined value in case there is no argument passed into the function or if the argument isundefinedwhen called.

function greeting (name = 'stranger') {
    console.log(`Hello, ${name}!`)  
} 
greeting('Nick')  // Output: Hello, Nick!  
greeting()  // Output: Hello, stranger!

Return

When a function is called, the computer will run through the function’s code and evaluate the result of calling the function. By default that resulting value is undefined.

function rectangleArea(width, height){
let  area = width * height  
}
console.log(rectangleArea(5,  7))  // Prints undefined

function monitorCount(rows,columns){
  return rows*columns
}
const numOfMonitors = monitorCount(5, 4)
console.log(numOfMonitors)

Helper Function

each function is carrying out a specific task, it makes our code easier to read and debug if necessary.

function multiplyByNineFifths(number) {
return number * (9/5);  };  function  getFahrenheit(celsius)  {  return  multiplyByNineFifths(celsius)  +  32;  };  getFahrenheit(15);  // Returns 59
function monitorCount(rows, columns) {
  return rows * columns;
}

function costOfMonitors(rows, columns){
  return monitorCount(rows, columns)*200;
}
const totalCost = costOfMonitors(5,4)
console.log(totalCost)

Function Expressions


另外一种声明函数的方法是function expression. 在expression中去定义一个函数,使用function作为关键字. 在function expression中,函数名经常被省略.一个没有名字的函数常称为anonymous function . function expression 常被存储在一个变量中in order to refer to it.

const plantNeedsWater = function(day){
  if(day === 'Wednesday'){
      return true
    }
  else{
    return false
  }
}

plantNeedsWater('Tuesday')
console.log(plantNeedsWater('Tuesday'))

Arrow Functions

  • example
const rectangleArea = (width, height) =>{
    let area = width\height
    return  area
};
const plantNeedsWater = (day) => {
  if (day === 'Wednesday') {
    return true;
  } else {
    return false;
  }
}

Concise Body Arrow Functions

  • Functions that take only a single parameter do not need that parameter to be enclosed in parentheses. However, if a function takes zero or multiple parameters, parentheses are required.

  • A function body composed of a single-line block does not need curly braces. Without the curly braces, whatever that line evaluates will be automatically returned. The contents of the block should immediately follow the arrow=>and thereturnkeyword can be removed. This is referred to as_implicit return_.

Laniakea
8 声望1 粉丝

ye