2 JavaScript Basics
Key Concepts
To master JavaScript basics, it is essential to understand the following key concepts:
- Variables and Data Types
- Functions
Variables and Data Types
Variables are containers for storing data values. In JavaScript, you can declare variables using the keywords var, let, or const. Each keyword has different scoping rules and usage scenarios. JavaScript supports several data types, including strings, numbers, booleans, objects, and arrays.
Example:
<script> let name = "John"; const age = 30; var isStudent = false; console.log(name); // Output: John console.log(age); // Output: 30 console.log(isStudent); // Output: false </script>
In this example, name is a string, age is a constant number, and isStudent is a boolean. The console.log function is used to display the values in the browser's console.
Functions
Functions are blocks of code designed to perform a particular task. They can be called multiple times within a program, making code reusable and modular. Functions can take parameters and return values.
Example:
<script> function greet(name) { return "Hello, " + name + "!"; } let greeting = greet("Alice"); console.log(greeting); // Output: Hello, Alice! </script>
In this example, the greet function takes a parameter name and returns a greeting message. The function is then called with the argument "Alice", and the result is stored in the variable greeting.
Functions can also be defined using arrow function syntax, which is more concise:
<script> const greet = (name) => "Hello, " + name + "!"; let greeting = greet("Bob"); console.log(greeting); // Output: Hello, Bob! </script>
Here, the arrow function greet achieves the same result as the traditional function but with a more compact syntax.
Understanding variables and data types, along with functions, forms the foundation of JavaScript programming. These concepts enable developers to write efficient, reusable, and maintainable code.