JS
JS
Variables :
let x = null;
var a;
Strings :
let single = 'Wheres my bandit hat?';
// => 21
console.log(single.length);
Arithmetic Operators
5 + 5 = 10 // Addition
10 - 5 = 5 // Subtraction
5 * 10 = 50 // Multiplication
10 / 5 = 2 // Division
10 % 5 = 0 // Modulo
Assignment Operators
let number = 100;
// Both statements will add 10
number = number + 10;
number += 10;
console.log(number);
// => 120
String Interpolation
let age = 7;
// String concatenation
'Tommy is ' + age + ' years old.';
// String interpolation
`Tommy is ${age} years old.`;
JavaScript Conditionals
if Statement
const isMailSent = true;
if (isMailSent) {
console.log('Mail sent to recipient');
}
Ternary Operator
var x=1;
// => true
result = (x == 1) ? true : false;
switch Statement
const food = 'salad';
switch (food) {
case 'oyster':
console.log('The taste of the sea');
break;
case 'pizza':
console.log('A delicious pie');
break;
default:
console.log('Enjoy your meal');
}
JavaScript ConditionalsJavaScript Functions
Functions
Anonymous Functions
// Named function
function rocketToMars() {
return 'BOOM!';
}
// Anonymous function
const rocketToMars = function() {
return 'BOOM!';
}
return Keyword
// With return
function sum(num1, num2) {
return num1 + num2;
}
// The function doesn't output the sum
function sum(num1, num2) {
num1 + num2;
}
Function Parameters
// The parameter is name
function sayHello(name) {
return `Hello, ${name}!`;
}
JavaScript Arrays
Arrays
const fruits = ["apple", "orange", "banana"];
// Different data types
const data = [1, 'chicken', false];
Property .length
const numbers = [1, 2, 3, 4];
numbers.length // 4
Mutable chart
push ✔ ✔
pop ✔ ✔
unshift ✔ ✔
shift ✔ ✔
Index
// Accessing an array element
const myArray = [100, 200, 300];
console.log(myArray[0]); // 100
console.log(myArray[1]); // 200
JavaScript Loops
For Loop
for (let i = 0; i < 4; i += 1) {
console.log(i);
};
// => 0, 1, 2, 3
JavaScript Events
Event Handling :
// Selecting an element
const button = document.getElementById('myButton'); || const button =
document.querySelector('#myButton');
// Adding an event listener
button.addEventListener('click', () => {
console.log('Button clicked!');
})
Type of Event :
Click / mouseover / keydown / change / click ……
JavaScript Value Manipulation
Value :
Inner HTML :
// Getting innerHTML
const div = document.getElementById('myDiv');
console.log(div.innerHTML);
// Setting innerHTML
div.innerHTML = '<strong>New HTML Content</strong>';
Text Content :
// Getting textContent
const paragraph = document.getElementById('myParagraph');
console.log(paragraph.textContent);
// Setting textContent
paragraph.textContent = 'New plain text content!';