JavaScript is a lightweight, interpreted programming language primarily used for creating dynamic and interactive web applications. It supports object-oriented, procedural, and functional programming styles.
- Dynamic Typing: Variables can hold different data types at runtime.
- First-Class Functions: Functions are treated as objects and can be assigned to variables, passed as arguments, or returned by other functions.
- Event-Driven: Executes code in response to user actions or system events.
- Prototypal Inheritance: Objects can inherit properties and methods from other objects.
- Declaration:
var
: Function-scoped (legacy).let
: Block-scoped.const
: Block-scoped, immutable reference.
- Example:
let name = "JavaScript"; const version = "ES6";
- Primitive:
string
,number
,boolean
,null
,undefined
,bigint
,symbol
- Reference:
object
,array
,function
- Arithmetic:
+
,-
,*
,/
,%
- Comparison:
==
,===
,!=
,!==
,<
,>
- Logical:
&&
,||
,!
- Assignment:
=
,+=
,-=
etc.
- Use
if
,else if
,else
, andswitch
for decision-making:if (age > 18) { console.log("Adult"); } else { console.log("Minor"); }
- For Loop:
for (let i = 0; i < 5; i++) { console.log(i); }
- While Loop:
let i = 0; while (i < 5) { console.log(i); i++; }
- Declaration:
function greet(name) { return `Hello, ${name}`; }
- Arrow Functions:
const greet = (name) => `Hello, ${name}`;
- Key-value pairs:
const person = { name: "Alice", age: 25 };
- Ordered collections:
const numbers = [1, 2, 3]; numbers.push(4);
- Selecting Elements:
const element = document.getElementById("myElement");
- Event Handling:
element.addEventListener("click", () => { console.log("Element clicked!"); });
- Promises:
fetch("https://api.example.com") .then((response) => response.json()) .then((data) => console.log(data)) .catch((error) => console.error(error));
- Async/Await:
async function fetchData() { const response = await fetch("https://api.example.com"); const data = await response.json(); console.log(data); }
- Use
try
,catch
, andfinally
for error handling:try { const data = JSON.parse("{invalid json}"); } catch (error) { console.error("Parsing error:", error); } finally { console.log("Done"); }
- Use
const
andlet
overvar
. - Avoid polluting the global namespace.
- Use strict equality (
===
) to avoid type coercion issues. - Modularize code using ES6 modules (
import
/export
).
- MDN Web Docs: https://developer.mozilla.org
- ECMAScript Specification: https://tc39.es
JavaScript is a versatile language used in a wide range of applications, from web development to server-side programming and beyond.