Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Javascript

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 5

<scrpit src="script.

js" defer><script> put in heading, instead of using async for


faster effect. If using jQuery avoid async
console.log(prompt("What is your name")), allow you to input an answer
console.log(confirm("Continue")), boolan value ok(true) and cancel(false)
console.warn console.error

Quote inside a string, let quote = "Liu said \"Hello\"."


console.log(quote); // Liu said "Hello".

let variable can change by, let favColor = "Red"; favColor = "Green";
console.log(favColor) // Green

Template Literals
let name = 'Liu'
let birthday = 7252002
without, let info = name + ' was born on this date ' + birthday + ' .'
with (much easier), let info2 = `${name} was born on this date ${birthday}`.

&&, ||, ?? nullish coalescing operator return first define value


or operator can't tell falsey values, return first true value
let score = 0; ?? can tell it is defined, not a falsy value
console.log(score || 'no score registered'); // ouput no score registered
console.log(score ?? 'no score registered'); // output 0

Find letter in string using bracket notation


let firstLetterOfLastName = ""; const lastName = "Lovelace";
firstLetterOfLastName = lastName[0]; // L

<script>Allow us to write Javascript code inside a HTML file</script>


-External File <script src="script"></script>

The HTML parser does NOT process the next element in the HTML file until it loads
and executes the <script> element, thus
leading to a delay in load time and resulting in a poor user experience.
Additionally, scripts are loaded sequentially, so if one script depends on another
script, they should be placed in that
very order inside the HTML file.

-LET, variable that can be reassigned a different value


JAVASCRIPT USE '' INSTEAD OF ""
let meal = 'Steak'; meal = 'Wings'; console.log(meal); // Wings
Var vs Let, only var can redeclare a value
LET and CONST are preferred over VAR
var game = 'Valorant'; var game = 'LoL'
-CONST, variable that cannot be reassigned a new value
console.log(game); // 'LoL'
const myName = 'Liu'; myName = 'Yihui'; console.log(myName); // Error let
game = 'Valorant'; let game = 'LoL' // Error
-Assigning value of one variable to another
let a; a = 13; let b; b = a; // b = 13

If statements are used to make decisions in code, tells JS to execute code under
certain conditions(boolean conditions)
>, >=, <, <= 6 < 5 // false '6' >= 5 // true
Equality operator(==) 3 == 3 // true 3 == '3' // true typeof
determine the type of a variable or value
Strict equality(===) 3 === 3 // true 3 === '3' // false type
3(number) type '3'(string)
function compareEquality(a, b) {
if (a === b) {
return "Equal";
}
return "Not Equal";
}
compareEquality(10, "10"); // false
Inequality operator(!=), returns false where equality would return true and vice
versa
1 != "1" // false 1 != 2 // true
Strict inquality operator, returns false where strict equality would return true
and vice versa
2 !== "2" // true 2 !== 2 // false

-Logical and operator(&&), returns true if and only if the operands to the left and
right of it are true
const randomNum = num => {
if (num > 5 && num < 10) {
return "Yes";
} else { return "No"; }
}; console.log(randomNum(1)) // "No"

-Logical or operator(||), returns true if either of the operands is true otherwise


it returns false
const randomNum = num => {
if (num < 10 || num > 20) {
return "Yes";
} else { return "No"; }
}; console.log(randomNum(1)) // "Yes

-IF ELSE, when a condition is false an alternate block of code can be executed
function testElse(val) {
let result = "";
if (val > 5) {
result = "Bigger than 5";
} else {
result = "5 or Smaller";
} return result;
};
console.log(testElse(5)) // output 5 or Smaller
if has (), if (val > 5) else does not have ()

-Shorter if...else statement(ternary operator)


let sale = true;
sale ? console.log("Buy") : console.log("Wait"); // output Buy

let age = 18
let message = age >= 18 ? 'can vote' : 'Sorry, can not vote'; // ouput can vote
condition ? [true] : [false]
-ELSE IF, more than 2 possible outcomes, multiple conditions that need to be
addressed
let stopLight = "yellow"; NOT A FUNCTION
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");
}; stopLight // output Slow down 'yellow'
else if has (), else if (val < 5)

-Order is important in if, else if statement


function foo(x) { function bar(x) {
if (x < 1) { if (x < 2) {
return "Less than one"; return "Less than two";
} else if (x < 2) { } else if (x < 1) {
return "Less than two"; return "Less than one";
} else { } else {
return "Greater than or equal to two"; return "Greater than or equal
to two";
} }; foo(0) // return Less than one } }; bar(0) // return
Less than two

-MATH, let num = 5; num += 1; same as num = num + 1; or num++ // output: 6


+=, *= , -=, /=
let a = 5.5; let b = 5.5; let divide = 6.9 /
5.3; (can perform calculations with decimal #)
a++; increase value by 1 b--; decrease value by 1
console.log(divide); // 1.3...
let string = "Hi"; string += " friend"; // output Hi friend everything
to the right of the equals sign is evaluated first
remainder %, let re = 10 % 3; console.log(re); // 1 do both
mathematical operation and assignment in one step
const andAdjective = "awesome!"; let ourStr = "freeCodeCamp is "; ourStr +=
andAdjective; // freeCodeCamp is awesome!

-property .length, tells us how many characters are in that string


Math.floor(), round to the nearest whole number
Math.random() * 25, generate a random number between 0 and 25

comment, single line (//) multiple line (/* ... */)

Scope is where a variable is declared and from where it can be accessed, vaiable
can have same name if declared in different code blocks
-Local Scope, only visble inside the function that they are created in, restricted
to being usable only inside that function, and are more secured
function game() { let title = 'Valorant'; console.log(title); } game(); //
Valorant if (true) { let title = 'Valorant'; console.log(title); }
// Valorant can't be use outside the function, only defined inside the funtion
not global console.log(title); // error

var only have functional scope can't work in if statements


function colour() { var c = 'Green'; } console.log(c); // error
if(true) { var c = 'Green'; } console.log(c) // Green, should be error as
variable is local scope and can only be used in the code block

-Global Scope, variables declared outside the function block or anywhere else
let company = 'Riot Games'; function game() { let title = 'Valorant';
console.log(title, company); } game(); // Valorant Riot Games
can be use anywhere console.log(company); // Riot Games
Local Scope takes precedence over the global scope
let processed = 0;
function processArg(num) {
return (num + 3) / 5; };
processed = processArg(7); console.log(processed) // output 2

Block scope, variable name crash


var x = 10;let sum = 0;
function addThree() {
sum += 3;
};

let x = 10; console.log(x); // 10 let x = 10; console.log(x);


// 10
if(true) { var x = 5; console.log(x); } // 5 if(true) { let x = 5;
console.log(x); } // 5
console.log(x); // 5 incorrect console.log(x); // 10 is correct because
the global scope should be refering to x outside the code block

-this keyword, 4 ways to be defined global object, method within an object,


constructor on a function or class, and a DOM event handler
a keyword used to reference the object that is executing the current function, this
is going to refer to the object calling the function
this by itself and within a function is excuted from the global scope, meaning the
object calling it is the windows object
function test() { console.log(this); } test(); // Window {window: Window, self:
Window, ...}

Method, function inside an object Method


${year} Error
let game = {name: 'Valorant', year: 2021, release: function () { console.log(`This
game was released in ${this.year}`); } };
game.release(); // 2021 release: function () { console.log(this);
} }; game.release(); // Game object {name: 'Valorant', ...}

this keyword in nested object


let game = { name: 'Valorant', year: 2021, characters: { duelist: 'Jett',
initiator: 'Sova', sentinel: 'Omen', controller: 'Sage',
list () { console.log(`${this.duelist}, ${this.initiator}, ${this.sentinel}, $
{this.control}`); } } };
game.characters.list(); // Jett, Sova, Omen, Sage

-Hoisting, javascript default behaviour where variables and function declarations


are moved to the top of their scope before code excution
meaning we can call function before we write them in our code, only declarations
are hoisted and not initialtion
Hoisting moves declarations only, initailzations/assignments are left in place,
var example; // D var example = 'Hi' // I/A
Variable Hoisting, undeclared variable is given value and typeof undefined at
excution, trying to use the variable author before we even defined it
Initializaion(something happening 'behind the scenes' at runtime all declared
variables are initialized with a beginning assignment of undefined)
var author; console.log('author'); author = 'J.K. Rowling';
// undefined what JS does behind the background
console.log(author); var author = 'J.K. Rowling'; // undefined, expected to be
error but JS somehow identify that there is a var called author
console.log(author); let author = 'J.K. Rowling'; // Error, Let and Const
prevent us from using undeclared variable/hoisting, advantage
let and const variable remain uninitialized at the beginning of excution whilst var
variable are initialized with the value of undefined

-Function hoisting, broswer scan through and found the function declaration and
pulled it to the top, ready to use
Declare, Invoke function lion('Aslan'); function lion(name)
{ console.log(`The lion's name is ${name}`); } // The lion's name is Aslan
Init, Invoke function lion('Aslan'); let lion = function(name)
{ console.log(`The lion's name is ${name}`); } // Error

You might also like