JavaScript Basics
Key Concepts
- Variables and Data Types
- Functions
- Conditional Statements
- Loops
Variables and Data Types
Variables are containers for storing data values. JavaScript has several data types, including strings, numbers, booleans, objects, and arrays. Variables are declared using the var
, let
, or const
keywords. For example, let name = "John";
declares a variable named name
with the value "John".
Functions
Functions are blocks of code designed to perform a particular task. They are executed when something invokes them. Functions can take parameters and return values. For example, function greet(name) { return "Hello, " + name; }
defines a function that takes a name and returns a greeting.
Conditional Statements
Conditional statements execute different actions based on different conditions. The most common conditional statements are if
, else if
, and else
. For example, if (age >= 18) { console.log("Adult"); } else { console.log("Minor"); }
checks if the age is 18 or older and logs "Adult" or "Minor" accordingly.
Loops
Loops are used to execute a block of code multiple times. The most common loops are for
and while
. For example, for (let i = 0; i < 5; i++) { console.log(i); }
logs the numbers 0 through 4 to the console.
Examples and Analogies
Think of variables as labeled boxes where you store different types of items. Functions are like recipes that take ingredients (parameters) and produce a dish (return value). Conditional statements are like decision trees where you choose a path based on conditions. Loops are like repeating a task until a condition is met, similar to washing dishes until the sink is empty.
Conclusion
Understanding these JavaScript basics is crucial for building interactive and dynamic web applications. By mastering variables, functions, conditional statements, and loops, you can create complex and responsive web pages.