JavaScript Basics
JavaScript is a versatile language that powers dynamic web content. Understanding its basic concepts is crucial to becoming a successful JavaScript developer. In this section, we will cover the fundamental elements of JavaScript programming.
Variables in JavaScript
Variables are used to store data that can be referenced and manipulated later in the program. In JavaScript, you can declare a variable using the var
, let
, or const
keywords.
- var: The older way of declaring variables (function-scoped).
- let: A more modern way to declare variables (block-scoped).
- const: Used to declare constants (values that cannot be reassigned).
let name = "John";
const age = 25;
var city = "New York";
Data Types in JavaScript
JavaScript supports several data types, which are classified into primitive and non-primitive types.
- String: Represents a sequence of characters.
- Number: Represents both integer and floating-point numbers.
- Boolean: Represents true or false.
- Object: A collection of key-value pairs, representing more complex data.
- Array: A special type of object used for storing ordered collections.
- Null: Represents the intentional absence of a value.
- Undefined: Represents a variable that has been declared but not yet assigned a value.
let person = {
name: "Alice",
age: 30
};
let numbers = [1, 2, 3, 4, 5];
Operators in JavaScript
JavaScript includes various operators to perform operations on variables and values. These include:
- Arithmetic Operators:
+
,-
,*
,/
,%
, and++
,--
. - Assignment Operators:
=
,+=
,-=
, etc. - Comparison Operators:
==
,===
,!=
,>
,<
, etc. - Logical Operators:
&&
(AND),||
(OR),!
(NOT).
let x = 10;
let y = 5;
let result = x + y; // result = 15
Functions in JavaScript
Functions are reusable blocks of code that perform a specific task. You can define functions using the function
keyword.
function greet(name) {
return "Hello, " + name;
}
console.log(greet("John")); // Output: Hello, John
In modern JavaScript, you can also define functions using arrow syntax:
const greet = (name) => {
return `Hello, ${name}`;
};
Control Flow: Conditionals
Conditional statements allow you to execute code based on certain conditions. The basic conditional statements in JavaScript are:
- if: Executes code if the condition is true.
- else: Executes code if the condition is false.
- else if: Tests another condition if the initial condition is false.
- switch: Allows multiple conditions to be tested.
let x = 10;
if (x > 5) {
console.log("x is greater than 5");
} else {
console.log("x is less than or equal to 5");
}
Conclusion
Understanding JavaScript basics such as variables, data types, operators, and functions is crucial for moving forward in web development. Once you grasp these fundamentals, you can start building more complex applications and logic.