JavaScript Basics
What is JavaScript?
JavaScript is a high-level, dynamic, untyped, and interpreted programming language. It is a core technology of the World Wide Web, alongside HTML and CSS. JavaScript enables interactive web pages and is an essential part of web applications.
JavaScript Syntax
JavaScript syntax refers to the set of rules that define a correctly structured JavaScript program. Below are some basic syntax examples:
// This is a single-line comment
/*
This is a multi-line comment
*/
console.log("Hello, World!"); // Outputs text to the console
Variables
Variables are containers for storing data values. In JavaScript, you can declare variables using var
, let
, or const
.
let name = "John"; // String
const age = 30; // Number
var isStudent = true; // Boolean
let
for variables that can change and const
for constants.
Data Types
JavaScript supports several data types:
- String
- Number
- Boolean
- Object
- Array
- Null
- Undefined
let str = "Hello";
let num = 100;
let isActive = true;
let obj = { name: "John", age: 30 };
let arr = [1, 2, 3];
Functions
A function is a block of code designed to perform a particular task. Functions are executed when they are invoked (called).
function greet(name) {
return "Hello, " + name;
}
console.log(greet("Alice")); // Outputs: Hello, Alice
Best Practices
Follow these best practices:
- Use
let
andconst
instead ofvar
. - Use descriptive variable names.
- Keep your code DRY (Don't Repeat Yourself).
- Comment your code for clarity.
- Use strict equality (===) instead of loose equality (==).
FAQ
What is the difference between let
and const
?
let
allows you to change the variable's value, while const
keeps the variable constant, preventing reassignment.
Can I use JavaScript for server-side programming?
Yes, with environments like Node.js, you can use JavaScript for server-side programming.