JavaScript (ES6+)_ Core Programming Language for Front-End Logic
JavaScript (ES6+)_ Core Programming Language for Front-End Logic
JavaScript (JS) is a programming language used to make web pages interactive. It enables
the dynamic manipulation of web content, allowing the creation of interactive websites, games,
applications, and more. JavaScript is the core language for front-end logic in web development.
It interacts with HTML (structure) and CSS (styling) to bring interactivity to web pages.
● Adds interactivity to web pages (e.g., form validation, pop-ups, dynamic content).
● Manipulates the DOM (Document Object Model) to dynamically update web content
without reloading the page.
● Allows handling of events like user clicks, form submissions, and mouse movements.
● Can be used for both front-end and back-end development (with Node.js).
● Supports modern features such as modules, promises, and async/await for handling
asynchronous code.
JavaScript syntax includes keywords, operators, data structures, control structures, and
functions. Let’s dive into the foundational aspects first.
Variables
js
CopyEdit
Data Types
Operators
● Arithmetic: +, -, *, /, %
Functions
Functions are blocks of code designed to perform a particular task. Functions are invoked or
called when needed.
Function Declaration:
js
CopyEdit
function greet(name) {
js
CopyEdit
console.log(add(2, 3)); // 5
Control Flow
Control flow structures like if-else, for loops, and while loops control the logic of the program.
If-else Statements
js
CopyEdit
} else {
Switch Case
js
CopyEdit
let day = 2;
switch (day) {
Loops
● For Loop:
js
CopyEdit
console.log(i); // Output: 0, 1, 2, 3, 4
}
● While Loop:
js
CopyEdit
let i = 0;
while (i < 5) {
console.log(i);
i++;
js
CopyEdit
// Accessing elements
console.log(arr[0]); // 1
// Array Methods
js
CopyEdit
let person = {
name: "Alice",
age: 25,
greet: function() {
};
ES6 Classes
Classes in JavaScript (introduced in ES6) are syntactic sugar for prototypes and are used to
create objects.
js
CopyEdit
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
greet() {
DOM Manipulation
JavaScript is heavily used to manipulate HTML content dynamically via the DOM (Document
Object Model).
js
CopyEdit
// Select an element
heading.classList.add('highlight');
Event Handling
JavaScript allows you to add interactive elements that respond to user input such as clicks,
typing, and more.
js
CopyEdit
button.addEventListener('click', function() {
alert('Button clicked!');
});
Promises
js
CopyEdit
if (success) resolve('Success!');
else reject('Failed!');
});
promise.then(function(result) {
}).catch(function(error) {
console.log(error);
});
Async/Await
js
CopyEdit
console.log(data);
}
fetchData();
Modules (ES6+)
JavaScript allows you to split your code into separate files called modules. This helps in
organizing and maintaining the codebase.
Exporting a module:
js
CopyEdit
// math.js
return a + b;
Importing a module:
js
CopyEdit
// main.js
Template Literals
js
CopyEdit
Destructuring
js
CopyEdit
js
CopyEdit
console.log(...arr); // Output: 1 2 3
js
CopyEdit
function sum(...args) {
By learning these concepts, you will have a strong understanding of JavaScript and can apply it
effectively to front-end web development, making your pages interactive and dynamic. Let me
know if you'd like to explore any concept further!
Let's go deeper into the remaining advanced concepts and some specialized features of
JavaScript that are often overlooked but essential for mastering the language.
1. Closures
A closure is a function that remembers its lexical environment even when the function is
executed outside that lexical environment. Closures allow for data encapsulation.
js
CopyEdit
function outerFunction(outerVariable) {
};
newFunction("inside");
// Output:
An IIFE is a function that runs as soon as it is defined. It’s mainly used for encapsulating code to
avoid polluting the global scope.
js
CopyEdit
(function() {
console.log("This is an IIFE");
})();
3. this Keyword
The value of this depends on the execution context (where the function is invoked).
● Global Context: this refers to the global object (Window in the browser).
● Object Method: this refers to the object that called the method.
● Event Listeners: this refers to the element that received the event.
js
CopyEdit
const person = {
name: "Alice",
greet() {
console.log(this.name); // "Alice"
},
};
person.greet(); // "Alice"
● call(): Calls a function with a given this value and arguments provided individually.
● bind(): Returns a new function, where the this value is bound to the argument
passed.
js
CopyEdit
function sayHello(age) {
In JavaScript, objects inherit properties from their prototype. All JavaScript objects have a
prototype, and JavaScript uses prototypes to share methods and properties between objects.
js
CopyEdit
function Person(name) {
this.name = name;
Person.prototype.greet = function() {
};
ES6 Classes are essentially syntactic sugar over JavaScript's prototype-based inheritance.
js
CopyEdit
yield "First";
yield "Second";
yield "Third";
(async () => {
console.log(value);
})();
7. Generators
Generators are a special type of function that can be paused and resumed. They are defined
using the function* syntax.
js
CopyEdit
function* generatorFunction() {
yield 'First';
yield 'Second';
yield 'Third';
console.log(generator.next().value); // "First"
console.log(generator.next().value); // "Second"
console.log(generator.next().value); // "Third"
Symbols are a new primitive type in JavaScript that are unique and immutable. Symbols are
often used to create unique keys in objects.
js
CopyEdit
● Map: Stores key-value pairs where keys can be any data type (similar to objects but with
more flexibility).
js
CopyEdit
// Map
map.set('name', 'Alice');
console.log(map.get('name')); // "Alice"
// Set
set.add(1);
set.add(2);
console.log(set.size); // 2
● WeakMap: Similar to Map, but keys must be objects, and they are "weakly held,"
meaning if the object is garbage collected, the entry is removed.
● WeakSet: Similar to Set, but stores only objects, and they are also weakly held.
js
CopyEdit
weakMap.set(obj, 'value');
JavaScript is single-threaded. The event loop is responsible for managing the execution of
code, collecting events, and executing queued tasks.
The call stack runs synchronous code, while promises and asynchronous operations are
placed in the task queue (or microtask queue).
js
CopyEdit
console.log('Start');
setTimeout(() => {
}, 0);
console.log('End');
// Output:
// Start
// End
// Promise
// Timeout
12. Modules (ES Modules)
Modern JavaScript uses the module system to split code into manageable chunks. You can
import/export modules across files.
js
CopyEdit
// Export (module.js)
console.log('Hello');
// Import (main.js)
console.log(name); // "John"
greet(); // "Hello"
This operator is used to assign default values when a variable is null or undefined.
js
CopyEdit
console.log(defaultValue); // "default"
14. Optional Chaining (?.)
The optional chaining operator (?.) allows you to safely access deeply nested object
properties without having to check each level manually.
js
CopyEdit
console.log(user.address?.zipcode); // undefined
These techniques are useful for optimizing performance when an event (like scroll or resize) is
fired multiple times per second.
js
CopyEdit
let timer;
return function() {
clearTimeout(timer);
};
}
● Throttling: Ensures a function is called at most once in a specified time interval.
js
CopyEdit
let inThrottle;
return function() {
if (!inThrottle) {
func();
inThrottle = true;
};
● Map and Set: Data structures for storing key-value pairs and unique values.
● WeakMap and WeakSet: Similar to Map/Set but for objects that can be garbage
collected.
These concepts should cover almost every corner of JavaScript, from basics to more advanced
topics. Let me know if you need further exploration into any of these areas!
Let's dive into a few additional advanced JavaScript concepts that are often considered
niche or highly specialized, but crucial for becoming a complete JavaScript master.
1. Memoization
js
CopyEdit
function memoize(fn) {
if (cache[key]) {
return cache[key];
} else {
cache[key] = result;
return result;
};
if (n === 0) return 1;
});
console.log(factorial(5)); // 120
js
CopyEdit
result.push(func(array[i]));
return result;
3. Currying
js
CopyEdit
function curry(fn) {
} else {
};
};
function sum(a, b, c) {
return a + b + c;
console.log(curriedSum(1)(2)(3)); // 6
In recursive functions, Tail Call Optimization (TCO) allows the last call of a function to be
optimized and avoids growing the stack. This helps improve the performance of recursive
functions.
js
CopyEdit
console.log(factorial(5)); // 120
Not all JavaScript engines support TCO yet, but it’s a useful concept to be aware of.
Typed Arrays provide a way to work with binary data directly in memory. These are especially
useful when working with file APIs, WebGL, or any low-level buffer manipulation.
js
CopyEdit
console.log(view[0]); // 255
While Promise.all() is widely used, there are a few more advanced Promise methods:
● Promise.allSettled(): Waits for all promises to settle (either resolve or reject) and
returns an array of the outcomes.
js
CopyEdit
const promises = [
Promise.resolve('Success'),
Promise.reject('Error'),
Promise.resolve('Another Success'),
];
Promise.allSettled(promises).then((results) =>
);
// Output:
// fulfilled
// rejected
// fulfilled
● Promise.race(): Returns the result of the first promise to settle (whether it resolves or
rejects).
js
CopyEdit
const promise1 = new Promise((resolve) => setTimeout(resolve, 500,
'One'));
The Proxy object allows you to create a proxy for another object and define custom behavior for
fundamental operations (e.g., property lookup, assignment, function invocation).
js
CopyEdit
const target = {
message1: "hello",
message2: "everyone",
};
const handler = {
return Reflect.get(...arguments);
},
};
console.log(proxy.message2); // "everyone"
Reflect provides built-in methods that mirror many proxy handlers, offering a default behavior
that you can enhance in a proxy.
The Intl API helps format numbers, dates, and strings according to different locales.
js
CopyEdit
console.log(new Intl.NumberFormat('de-DE').format(number)); //
"1.234.567,89"
// Format date
console.log(new Intl.DateTimeFormat('en-GB').format(date)); //
"28/03/2025"
9. WeakRef and FinalizationRegistry (ES2021)
WeakRef allows you to hold weak references to objects, and FinalizationRegistry allows you
to register a callback when an object is garbage collected. These are useful for managing
memory in advanced applications.
js
CopyEdit
});
Introduced in ES2022, the at() method allows you to access array/string elements using both
positive and negative indices.
js
CopyEdit
Starting in ES2022, you can use the await keyword at the top level of a module (without
wrapping it in an async function).
js
CopyEdit
console.log(data);
12. BigInt
BigInt is a new data type in JavaScript to represent integers beyond the safe integer limit for the
Number type (2^53 - 1).
js
CopyEdit
Pattern matching is a proposed feature (still under development) that is similar to switch
statements, but designed for more complex matching.
js
CopyEdit
match (value) {
JavaScript now supports private fields and methods in classes using the # prefix.
js
CopyEdit
class MyClass {
#privateField = 42;
#privateMethod() {
}
publicMethod() {
return this.#privateMethod();
In ES2021, you have nullish assignment and logical assignment operators to shorten
common assignment patterns.
js
CopyEdit
let x = null;
console.log(x); // 10
let y = true;
console.log(y); // false
let z = false;
z ||= true; // Logical OR assignment
console.log(z); // true
Quirky Behaviors of JS
Examples:
js
CopyEdit
2. Type Coercion
Examples:
js
CopyEdit
● false
● 0
● null
● undefined
● NaN
Everything else is truthy, even empty objects ({}) and empty arrays
([]).
Examples:
js
CopyEdit
Boolean(0); // false
Boolean(''); // false
Boolean(null); // false
Boolean(undefined); // false
Boolean(NaN); // false
// Logical examples
if ([]) {
console.log("Empty array is truthy!"); // This will run
if ({}) {
Examples:
js
CopyEdit
NaN === NaN; // false (NaN is never equal to anything, not even
itself)
isNaN(NaN); // true
Number.isNaN(NaN); // true
Examples:
js
CopyEdit
Examples:
js
CopyEdit
1 + 2; // 3 (addition)
Examples:
js
CopyEdit
Example:
js
CopyEdit
let a =
b: 1
};
let b = {
c: 1
};
Example:
js
CopyEdit
Example:
js
CopyEdit
Example:
js
CopyEdit
function foo() {
console.log("Hello");
console.log("Hi");
};
Example:
js
CopyEdit
function test() {
test();
Examples:
js
CopyEdit
function test() {
console.log(this);
let obj = {
method: test,
};
Example:
js
CopyEdit
function example(a, b) {
console.log(arguments[0]); // 1
console.log(arguments[1]); // 2
example(1, 2);
example2();
Conclusion