Mastering 150 JavaScript Core Instructions
DataScienceQA Comprehensive Guide to 150 Core JavaScript Instructions
What is JavaScript?
JavaScript (JS) is a high-level, often just-in-time compiled, and multi-paradigm programming language. It is one of the core technologies of the World Wide Web, alongside HTML and CSS. It enables interactive web pages and is an essential part of web applications.
Use Cases for JavaScript:
• Front-End Web Development: Creating interactive user interfaces and dynamic web pages (DOM manipulation, animations, form validation).
• Back-End Web Development: Building server-side applications using environments like Node.js.
• Mobile App Development: Creating cross-platform mobile apps with frameworks like React Native and NativeScript.
• Desktop App Development: Building desktop applications with frameworks like Electron.
• Game Development: Creating browser-based games.
• Web Servers and Server Applications: Building network applications using Node.js.
Alternatives to JavaScript:
• TypeScript: A superset of JavaScript that adds static types, making it more robust for large-scale applications. It compiles down to plain JavaScript.
• Dart: A language developed by Google, often used with the Flutter framework for building cross-platform mobile, web, and desktop applications.
• WebAssembly (Wasm): A binary instruction format that allows code written in languages like C++, C#, and Rust to run in the browser at near-native speed. It's meant to complement, not replace, JavaScript.
• Python (with frameworks): While not a direct browser alternative, languages like Python (with Django/Flask) are used for the backend, performing tasks that Node.js would.
---
Core Concepts & Variables
• // Single-line comment
Explanation: Ignores everything on the line after //. Used for notes.
// This is a single-line comment
let x = 10; // This part is a comment• /* */ Multi-line comment
Explanation: Ignores everything between /* and */.
/*
This is a multi-line comment.
It can span across several lines.
*/• var
Explanation: The old way to declare a variable. It's function-scoped.
var score = 100;
console.log(score); // Output: 100• let
Explanation: Declares a block-scoped variable that can be reassigned.
let age = 25;
age = 26;
console.log(age); // Output: 26• const
Explanation: Declares a block-scoped constant whose value cannot be reassigned.
const PI = 3.14;
// PI = 3.14159; // This would cause an error
console.log(PI); // Output: 3.14• console.log()
Explanation: Outputs a message to the web console. Essential for debugging.
console.log("Hello, World!");Data Types
• String
Explanation: A sequence of characters.
let greeting = "Hello";
let name = 'Alice';• Number
Explanation: Represents both integer and floating-point numbers.
let integer = 10;
let float = 10.5;• Boolean
Explanation: Represents a logical entity and can have two values: true or false.
let isLoggedIn = true;
let hasPermission = false;• null
Explanation: Represents the intentional absence of any object value.
let user = null;• undefined
Explanation: A variable that has been declared but has not yet been assigned a value.
let userRole;
console.log(userRole); // Output: undefined• Object
Explanation: A collection of key-value pairs.
let person = {
firstName: "John",
lastName: "Doe"
};• Array
Explanation: A special type of object used to store ordered collections of data.
let fruits = ["Apple", "Banana", "Cherry"];• typeof
Explanation: An operator that returns a string indicating the type of the unevaluated operand.
console.log(typeof "Hello"); // Output: "string"
console.log(typeof 123); // Output: "number"
console.log(typeof true); // Output: "boolean"Operators
• = (Assignment)
Explanation: Assigns a value to a variable.
let x = 10;• + (Addition)
Explanation: Adds two numbers or concatenates two strings.
let sum = 5 + 3; // 8
let message = "Hello" + " " + "World"; // "Hello World"• - (Subtraction)
Explanation: Subtracts one number from another.
let difference = 10 - 4; // 6• * (Multiplication)
Explanation: Multiplies two numbers.
let product = 5 * 6; // 30• / (Division)
Explanation: Divides one number by another.
let quotient = 20 / 4; // 5• % (Modulus/Remainder)
Explanation: Returns the remainder of a division.
let remainder = 10 % 3; // 1• ** (Exponentiation)
Explanation: Raises the first operand to the power of the second operand.
let power = 2 ** 3; // 8 (2*2*2)• ++ (Increment)
Explanation: Increases a numeric variable by one.
let count = 5;
count++; // count is now 6• -- (Decrement)
Explanation: Decreases a numeric variable by one.
let count = 5;
count--; // count is now 4• += (Addition Assignment)
Explanation: Adds a value to a variable and assigns the result to that variable.
let score = 10;
score += 5; // score is now 15• == (Loose Equality)
Explanation: Checks if two values are equal, performing type coercion. (Avoid using this).
console.log(5 == "5"); // Output: true• === (Strict Equality)
Explanation: Checks if two values are equal and of the same type. (Preferred method).
console.log(5 === "5"); // Output: false
console.log(5 === 5); // Output: true• != (Loose Inequality)
Explanation: Checks if two values are not equal, with type coercion.
console.log(5 != "5"); // Output: false• !== (Strict Inequality)
Explanation: Checks if two values are not equal or not of the same type.
console.log(5 !== "5"); // Output: true• > (Greater Than)
Explanation: Checks if the left operand is greater than the right.
console.log(10 > 5); // Output: true• < (Less Than)
Explanation: Checks if the left operand is less than the right.
console.log(10 < 5); // Output: false• >= (Greater Than or Equal To)
Explanation: Checks if the left operand is greater than or equal to the right.
console.log(5 >= 5); // Output: true• <= (Less Than or Equal To)
Explanation: Checks if the left operand is less than or equal to the right.
console.log(5 <= 4); // Output: false• && (Logical AND)
Explanation: Returns true only if both operands are true.
let isAdult = true;
let hasLicense = true;
console.log(isAdult && hasLicense); // Output: true• || (Logical OR)
Explanation: Returns true if at least one of the operands is true.
let hasCoffee = true;
let hasTea = false;
console.log(hasCoffee || hasTea); // Output: true• ! (Logical NOT)
Explanation: Reverses the boolean value of an operand.
let isRaining = true;
console.log(!isRaining); // Output: falseControl Flow
• if
Explanation: Executes a block of code if a specified condition is true.
let temp = 25;
if (temp > 20) {
console.log("It's a warm day.");
}• else
Explanation: Executes a block of code if the if condition is false.
let temp = 15;
if (temp > 20) {
console.log("It's a warm day.");
} else {
console.log("It's a cool day.");
}• else if
Explanation: Specifies a new condition to test, if the first if condition is false.
let score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else {
console.log("Grade: C or lower");
}• switch
Explanation: Evaluates an expression and executes code blocks based on a matching case.
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the work week.");
break;
case "Friday":
console.log("End of the work week.");
break;
default:
console.log("It's a regular day.");
}• for loop
Explanation: Repeats a block of code a specified number of times.
for (let i = 0; i < 5; i++) {
console.log("Number is " + i);
}• while loop
Explanation: Repeats a block of code as long as a specified condition is true.
let i = 0;
while (i < 5) {
console.log("Number is " + i);
i++;
}• do...while loop
Explanation: Repeats a block of code once, and then continues as long as a condition is true.
let i = 0;
do {
console.log("Number is " + i);
i++;
} while (i < 5);• break
Explanation: "Jumps out" of a loop or a switch statement.
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Stops the loop when i is 5
}
console.log(i);
}• continue
Explanation: "Jumps over" one iteration in the loop and continues with the next.
for (let i = 0; i < 5; i++) {
if (i === 2) {
continue; // Skips the rest of the code for this iteration
}
console.log(i); // Will not print 2
}Functions
• function declaration
Explanation: Defines a function with the specified parameters.
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!• return
Explanation: Stops the execution of a function and returns a value from that function.
function add(a, b) {
return a + b;
}
let result = add(5, 3);
console.log(result); // Output: 8• Function expression
Explanation: A function can also be defined using an expression and assigned to a variable.
const greet = function(name) {
console.log("Hello, " + name);
};
greet("Bob");• Arrow function
Explanation: A more concise syntax for writing function expressions.
const multiply = (a, b) => {
return a * b;
};
// Even shorter if it's a single return statement
const subtract = (a, b) => a - b;• Default parameters
Explanation: Allows formal parameters to be initialized with default values if no value is passed.
function greet(name = "Guest") {
console.log("Hello, " + name);
}
greet(); // Output: Hello, Guest
greet("Charlie"); // Output: Hello, CharlieStrings
• string.length
Explanation: Returns the number of characters in a string.
let text = "Hello";
console.log(text.length); // Output: 5• Template Literals ()
Explanation: Allows for embedded expressions and multi-line strings.
let name = "Alice";
let age = 30;
let message = `My name is ${name} and I am ${age} years old.`;
console.log(message);• string.toUpperCase()
Explanation: Converts a string to uppercase letters.
let text = "hello world";
console.log(text.toUpperCase()); // Output: "HELLO WORLD"• string.toLowerCase()
Explanation: Converts a string to lowercase letters.
let text = "HELLO WORLD";
console.log(text.toLowerCase()); // Output: "hello world"• string.indexOf()
Explanation: Returns the index (position) of the first occurrence of a specified text in a string.
let text = "Hello world, welcome to the world.";
console.log(text.indexOf("world")); // Output: 6• string.slice()
Explanation: Extracts a part of a string and returns the extracted part in a new string.
let text = "Apple, Banana, Kiwi";
let part = text.slice(7, 13); // from index 7 to 12
console.log(part); // Output: "Banana"• string.replace()
Explanation: Replaces a specified value with another value in a string.
let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "W3Schools");
console.log(newText);• string.split()
Explanation: Splits a string into an array of substrings.
let text = "a,b,c,d,e";
const myArray = text.split(",");
console.log(myArray[0]); // Output: "a"• string.trim()
Explanation: Removes whitespace from both sides of a string.
let text = " Hello World! ";
console.log(text.trim()); // Output: "Hello World!"• string.includes()
Explanation: Returns true if a string contains a specified value.
let text = "Hello world, welcome to the universe.";
console.log(text.includes("world")); // Output: true• string.startsWith()
Explanation: Returns true if a string begins with a specified value.
let text = "Hello world";
console.log(text.startsWith("Hello")); // Output: true• string.endsWith()
Explanation: Returns true if a string ends with a specified value.
let text = "John Doe";
console.log(text.endsWith("Doe")); // Output: true• string.charAt()
Explanation: Returns the character at a specified index (position) in a string.
let text = "HELLO WORLD";
console.log(text.charAt(0)); // Output: "H"Numbers and Math
• parseInt()
Explanation: Parses a string and returns a whole number (integer).
let numStr = "10.5 apples";
console.log(parseInt(numStr)); // Output: 10• parseFloat()
Explanation: Parses a string and returns a floating-point number.
let numStr = "10.33";
console.log(parseFloat(numStr)); // Output: 10.33• isNaN()
Explanation: Determines whether a value is NaN (Not-a-Number).
console.log(isNaN("Hello")); // Output: true
console.log(isNaN(123)); // Output: false• number.toFixed()
Explanation: Formats a number using fixed-point notation (rounds to a specified number of decimals).
let num = 5.56789;
console.log(num.toFixed(2)); // Output: "5.57"• Math.random()
Explanation: Returns a random number between 0 (inclusive) and 1 (exclusive).
console.log(Math.random()); // e.g., 0.123456789• Math.floor()
Explanation: Rounds a number DOWN to the nearest integer.
console.log(Math.floor(4.9)); // Output: 4• Math.ceil()
Explanation: Rounds a number UP to the nearest integer.
console.log(Math.ceil(4.1)); // Output: 5• Math.round()
Explanation: Rounds a number to the nearest integer.
console.log(Math.round(4.6)); // Output: 5
console.log(Math.round(4.4)); // Output: 4• Math.max()
Explanation: Returns the number with the highest value among its arguments.
console.log(Math.max(0, 150, 30, 20, -8)); // Output: 150• Math.min()
Explanation: Returns the number with the lowest value among its arguments.
console.log(Math.min(0, 150, 30, 20, -8)); // Output: -8Arrays
• array.length
Explanation: Returns the number of elements in an array.
const fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits.length); // Output: 3• Accessing an array element
Explanation: Use bracket notation [] with the index (position) of the element.
const fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // Output: "Apple"• array.push()
Explanation: Adds a new element to the END of an array.
const fruits = ["Apple", "Banana"];
fruits.push("Cherry");
console.log(fruits); // Output: ["Apple", "Banana", "Cherry"]• array.pop()
Explanation: Removes the LAST element from an array.
const fruits = ["Apple", "Banana", "Cherry"];
fruits.pop();
console.log(fruits); // Output: ["Apple", "Banana"]• array.shift()
Explanation: Removes the FIRST element from an array.
const fruits = ["Apple", "Banana", "Cherry"];
fruits.shift();
console.log(fruits); // Output: ["Banana", "Cherry"]• array.unshift()
Explanation: Adds a new element to the BEGINNING of an array.
const fruits = ["Banana", "Cherry"];
fruits.unshift("Apple");
console.log(fruits); // Output: ["Apple", "Banana", "Cherry"]• array.forEach()
Explanation: Executes a provided function once for each array element.
const numbers = [1, 2, 3];
numbers.forEach(num => {
console.log(num * 2); // Output: 2, 4, 6 (on separate lines)
});• array.map()
Explanation: Creates a new array by performing a function on each array element.
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6]• array.filter()
Explanation: Creates a new array with all elements that pass the test implemented by the provided function.
const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // Output: [2, 4, 6]• array.reduce()
Explanation: Reduces the array to a single value by executing a function for each element.
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, current) => accumulator + current, 0);
console.log(sum); // Output: 10• array.find()
Explanation: Returns the value of the first element in an array that passes a test.
const numbers = [10, 20, 30, 40];
const found = numbers.find(num => num > 25);
console.log(found); // Output: 30• array.findIndex()
Explanation: Returns the index of the first element in an array that passes a test.
const numbers = [10, 20, 30, 40];
const index = numbers.findIndex(num => num > 25);
console.log(index); // Output: 2• array.includes()
Explanation: Determines whether an array includes a certain value.
const fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits.includes("Banana")); // Output: true• array.join()
Explanation: Joins all elements of an array into a string.
const fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits.join(", ")); // Output: "Apple, Banana, Cherry"• array.slice()
Explanation: Returns a shallow copy of a portion of an array into a new array object.
const fruits = ["Apple", "Banana", "Cherry", "Date"];
const citrus = fruits.slice(1, 3); // from index 1 to 2
console.log(citrus); // Output: ["Banana", "Cherry"]• array.splice()
Explanation: Adds/Removes items to/from an array, and returns the removed item(s).
const fruits = ["Apple", "Banana", "Date"];
// At index 2, remove 0 elements, and add "Cherry"
fruits.splice(2, 0, "Cherry");
console.log(fruits); // Output: ["Apple", "Banana", "Cherry", "Date"]• Array.isArray()
Explanation: Determines whether the passed value is an Array.
const fruits = ["Apple"];
const person = { name: "John" };
console.log(Array.isArray(fruits)); // Output: true
console.log(Array.isArray(person)); // Output: false• array.sort()
Explanation: Sorts the elements of an array in place.
const fruits = ["Banana", "Apple", "Cherry"];
fruits.sort();
console.log(fruits); // Output: ["Apple", "Banana", "Cherry"]Objects
• Object literal
Explanation: The most common way to create an object, using curly braces {}.
const car = {
make: "Toyota",
model: "Camry",
year: 2021
};• Dot notation
Explanation: Accessing an object's property using a dot ..
const car = { make: "Toyota", model: "Camry" };
console.log(car.make); // Output: "Toyota"• Bracket notation
Explanation: Accessing an object's property using brackets [] and a string key.
const car = { make: "Toyota", model: "Camry" };
console.log(car["model"]); // Output: "Camry"• Object method
Explanation: A function that is a property of an object.
const person = {
name: "Alice",
greet: function() {
console.log("Hello, my name is " + this.name);
}
};
person.greet(); // Output: "Hello, my name is Alice"• this keyword
Explanation: Refers to the object that is executing the current function.
const person = {
name: "Bob",
// 'this' refers to the 'person' object
sayName: function() { console.log(this.name); }
};
person.sayName(); // Output: "Bob"• Object.keys()
Explanation: Returns an array of a given object's own property names.
const car = { make: "Toyota", model: "Camry", year: 2021 };
console.log(Object.keys(car)); // Output: ["make", "model", "year"]• Object.values()
Explanation: Returns an array of a given object's own property values.
const car = { make: "Toyota", model: "Camry", year: 2021 };
console.log(Object.values(car)); // Output: ["Toyota", "Camry", 2021]• Object.entries()
Explanation: Returns an array of a given object's own key-value pairs.
const car = { make: "Toyota", model: "Camry" };
console.log(Object.entries(car)); // Output: [["make", "Toyota"], ["model", "Camry"]]ES6+ Features
• Spread Operator (...) for arrays
Explanation: Allows an iterable such as an array to be expanded in places where zero or more arguments or elements are expected.
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // Output: [1, 2, 3, 4, 5]• Spread Operator (...) for objects
Explanation: Copies the properties from one object into another.
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
console.log(obj2); // Output: { a: 1, b: 2, c: 3 }• Rest Parameter (...)
Explanation: Represents an indefinite number of arguments as an array.
function sum(...numbers) {
return numbers.reduce((acc, current) => acc + current, 0);
}
console.log(sum(1, 2, 3, 4)); // Output: 10• Object Destructuring
Explanation: A convenient way of extracting properties from objects into variables.
const person = { firstName: "John", lastName: "Doe" };
const { firstName, lastName } = person;
console.log(firstName); // Output: "John"• Array Destructuring
Explanation: A convenient way of extracting elements from arrays into variables.
const fruits = ["Apple", "Banana", "Cherry"];
const [first, second] = fruits;
console.log(first); // Output: "Apple"Asynchronous JavaScript
• setTimeout()
Explanation: Executes a function after waiting a specified number of milliseconds.
setTimeout(() => {
console.log("This message is shown after 2 seconds.");
}, 2000);• setInterval()
Explanation: Repeats a given function at every given time-interval.
// This would log "Hello" every second.
// Use clearInterval to stop it.
// setInterval(() => { console.log("Hello"); }, 1000);• clearTimeout()
Explanation: Stops the execution of a function specified in setTimeout().
const myTimeout = setTimeout(() => {
console.log("This will not run.");
}, 2000);
clearTimeout(myTimeout);• clearInterval()
Explanation: Stops the executions of a function specified in setInterval().
let count = 0;
const myInterval = setInterval(() => {
console.log("Count: " + count++);
if (count > 3) {
clearInterval(myInterval);
}
}, 500);• Promise
Explanation: An object representing the eventual completion or failure of an asynchronous operation.
const myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Operation was successful!");
} else {
reject("Operation failed.");
}
});• .then()
Explanation: Schedules a function to be called when the promise is fulfilled (resolved).
myPromise.then((message) => {
console.log(message); // Output if resolved: "Operation was successful!"
});• .catch()
Explanation: Schedules a function to be called when the promise is rejected.
myPromise.catch((error) => {
console.error(error); // Output if rejected: "Operation failed."
});• async
Explanation: The async keyword before a function makes it return a promise.
async function myAsyncFunction() {
return "Hello from async!";
}
myAsyncFunction().then(console.log);• await
Explanation: The await keyword pauses the execution of an async function and waits for a promise to resolve.
async function fetchData() {
console.log("Fetching data...");
const response = await fetch('https://api.github.com/users/github');
const data = await response.json();
console.log(data.name); // Output: "GitHub"
}
fetchData();• fetch() API
Explanation: A modern interface for fetching resources across the network (e.g., from an API).
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json.title)); // Output: "delectus aut autem"DOM Manipulation (for Browsers)
• document.getElementById()
Explanation: Selects an element by its unique ID.
// Assuming HTML: <p id="demo"></p>
const element = document.getElementById("demo");• document.querySelector()
Explanation: Returns the first element that matches a specified CSS selector.
// Assuming HTML: <div class="container"><p>First</p></div>
const p = document.querySelector(".container p");• document.querySelectorAll()
Explanation: Returns all elements that match a specified CSS selector, as a NodeList.
// Assuming HTML: <ul><li>1</li><li>2</li></ul>
const items = document.querySelectorAll("li");• .innerHTML
Explanation: Gets or sets the HTML content (including tags) of an element.
// Assuming HTML: <p id="demo"></p>
const p = document.getElementById("demo");
p.innerHTML = "<strong>Hello World!</strong>";• .textContent
Explanation: Gets or sets the text content of an element, ignoring HTML tags.
// Assuming HTML: <p id="demo"><strong>Old Text</strong></p>
const p = document.getElementById("demo");
p.textContent = "New Plain Text";• .style
Explanation: Accesses the inline style of an element to change its CSS properties.
// Assuming HTML: <p id="demo"></p>
const p = document.getElementById("demo");
p.style.color = "blue";
p.style.fontSize = "24px";• .addEventListener()
Explanation: Attaches an event handler (a function) to an element.
// Assuming HTML: <button id="myBtn">Click me</button>
const btn = document.getElementById("myBtn");
btn.addEventListener("click", () => {
alert("Button was clicked!");
});• document.createElement()
Explanation: Creates a new HTML element.
const newDiv = document.createElement("div");• .appendChild()
Explanation: Appends a node (element) as the last child of a parent node.
// Assuming HTML: <div id="container"></div>
const container = document.getElementById("container");
const newP = document.createElement("p");
newP.textContent = "This is a new paragraph.";
container.appendChild(newP);• .removeChild()
Explanation: Removes a child node from the DOM.
// Assuming the setup from the previous example
// container.removeChild(newP);• .classList.add()
Explanation: Adds one or more class names to an element.
// Assuming HTML: <div id="myDiv"></div>
const div = document.getElementById("myDiv");
div.classList.add("active", "highlight");• .classList.remove()
Explanation: Removes one or more class names from an element.
// Assuming HTML: <div id="myDiv" class="active highlight"></div>
const div = document.getElementById("myDiv");
div.classList.remove("highlight");• .classList.toggle()
Explanation: Toggles a class name for an element (adds it if it doesn't exist, removes it if it does).
// Assuming HTML: <button id="toggleBtn">Toggle</button>
// const btn = document.getElementById("toggleBtn");
// btn.addEventListener("click", () => {
// document.body.classList.toggle("dark-mode");
// });Error Handling
• try
Explanation: Defines a block of code to be tested for errors while it is being executed.
try {
// Code that might throw an error
let result = someUndefinedFunction();
} catch (error) {
console.log("An error occurred!");
}• catch
Explanation: Defines a block of code to be executed if an error occurs in the try block.
try {
// ...
} catch (err) {
console.error("Error name: " + err.name);
console.error("Error message: " + err.message);
}• finally
Explanation: Defines a block of code to be executed regardless of the try/catch result.
try {
console.log("Trying...");
} catch (err) {
console.log("Caught an error.");
} finally {
console.log("This will always run.");
}• throw
Explanation: Creates a custom error.
function checkAge(age) {
if (age < 18) {
throw new Error("Access denied - must be 18 or older.");
}
return "Access granted.";
}
// console.log(checkAge(15)); // This would throw an errorJSON
• JSON.stringify()
Explanation: Converts a JavaScript object into a JSON string.
const user = { name: "Alice", age: 30 };
const jsonString = JSON.stringify(user);
console.log(jsonString); // Output: '{"name":"Alice","age":30}'• JSON.parse()
Explanation: Parses a JSON string, constructing the JavaScript value or object described by the string.
const jsonString = '{"name":"Alice","age":30}';
const userObject = JSON.parse(jsonString);
console.log(userObject.name); // Output: "Alice"Miscellaneous
• Date object
Explanation: Used to work with dates and times.
const now = new Date();
console.log(now); // Shows the current date and time• date.getFullYear()
Explanation: Gets the year as a four-digit number.
const d = new Date();
console.log(d.getFullYear()); // e.g., 2023• date.getMonth()
Explanation: Gets the month as a number (0-11).
const d = new Date();
console.log(d.getMonth()); // January is 0, December is 11• date.getDate()
Explanation: Gets the day as a number (1-31).
const d = new Date();
console.log(d.getDate());• date.getHours()
Explanation: Gets the hour (0-23).
const d = new Date();
console.log(d.getHours());• date.getMinutes()
Explanation: Gets the minute (0-59).
const d = new Date();
console.log(d.getMinutes());• localStorage.setItem()
Explanation: Stores data in the browser's local storage with no expiration date.
localStorage.setItem("username", "JohnDoe");• localStorage.getItem()
Explanation: Retrieves data from local storage.
const username = localStorage.getItem("username");
console.log(username); // Output: "JohnDoe"• localStorage.removeItem()
Explanation: Removes an item from local storage.
localStorage.removeItem("username");• sessionStorage.setItem()
Explanation: Stores data for one session (data is lost when the browser tab is closed).
sessionStorage.setItem("sessionID", "12345");• Regular Expression
Explanation: An object that describes a pattern of characters, used for pattern-matching or search-and-replace functions on text.
let text = "Visit W3Schools!";
let n = text.search(/w3schools/i); // 'i' is for case-insensitive
console.log(n); // Output: 6• class
Explanation: A template for creating objects.
class Car {
constructor(name) {
this.name = name;
}
honk() {
return `${this.name} says: Honk!`;
}
}• constructor method
Explanation: A special method for creating and initializing an object created with a class.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const person1 = new Person("Alice", 25);• new keyword
Explanation: Creates an instance of an object that has a constructor function.
// Using the 'Person' class from the previous example
const person2 = new Person("Bob", 30);
console.log(person2.name); // Output: Bob• extends
Explanation: Used in class declarations to create a class as a child of another class.
class Model extends Car {
constructor(name, mod) {
super(name); // Call the parent constructor
this.model = mod;
}
}• super
Explanation: Used to call the constructor of its parent class to access the parent's properties and methods.
// Using the 'Model' class from the previous example
const myCar = new Model("Ford", "Mustang");
console.log(myCar.honk()); // Output: Ford says: Honk!• import
Explanation: Used to import functions, objects, or primitives that have been exported from an external module.
// In file: main.js
// import { greet } from './greetings.js';
// greet("World");• export
Explanation: Used when creating JavaScript modules to export functions, objects, or primitive values from the module so they can be used by other programs.
// In file: greetings.js
// export function greet(name) {
// console.log(`Hello, ${name}!`);
// }#JavaScript #JS #Programming #WebDevelopment #LearnToCode #JSCourse