JavaScript is a versatile, high-level programming language used primarily for web development.
Its syntax is relatively straightforward and is crucial for writing effective code. Here's a brief overview:
Variables: Declared using
var
,let
, orconst
.var
has function scope, whilelet
andconst
have block scope.const
is used for constants.let name = "Alice"; const age = 30;
Data Types: JavaScript has several data types, including strings, numbers, booleans, arrays, objects,
null
, andundefined
.let isStudent = true; let score = 95.5; let user = { name: "Bob", age: 25 };
Functions: Functions are declared using the
function
keyword or as arrow functions.function greet() { console.log("Hello!"); } const add = (a, b) => a + b;
Conditionals: Use
if
,else if
, andelse
to handle conditions.switch
can be used for multiple conditions.if (score > 90) { console.log("Excellent"); } else { console.log("Good"); } switch (day) { case "Monday": console.log("Start of the week"); break; default: console.log("Other day"); }
Loops:
for
,while
, anddo...while
loops are used for iteration.for (let i = 0; i < 5; i++) { console.log(i); } let j = 0; while (j < 5) { console.log(j); j++; }
Objects and Arrays: Arrays are ordered collections; objects are key-value pairs.
let fruits = ["apple", "banana", "cherry"]; let person = { name: "Alice", age: 30 };
Classes: JavaScript supports object-oriented programming with
class
.class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} makes a noise.`); } } let dog = new Animal("Dog"); dog.speak();
Template Literals: Used for string interpolation and multi-line strings.
let greeting = `Hello, ${name}!`;
Error Handling: Use
try
,catch
, andfinally
for error management.try { throw new Error("Something went wrong"); } catch (e) { console.error(e.message); } finally { console.log("Cleanup"); }
Events: Handling events in the DOM.
document.getElementById("myButton").addEventListener("click", function() { alert("Button clicked!"); });
These examples highlight the core aspects of JavaScript syntax and usage.