JavaScript is a programming language that is used to create interactive and dynamic web pages. Here are some key syntax rules to keep in mind when writing JavaScript code:
- Comments: To add comments in JavaScript, use the “//” symbol for a single-line comment, or use “/* */” for a multi-line comment.
- Variables: Use the “var”, “let”, or “const” keyword to declare variables. For example:
var x = 10; let y = "hello"; const z = true;- Data Types: JavaScript supports several data types, including numbers, strings, booleans, null, and undefined.
- Operators: Use operators such as “+” for addition, “-” for subtraction, “*” for multiplication, “/” for division, and “%” for modulus.
- Conditionals: Use conditional statements such as “if”, “else if”, and “else” to execute code based on certain conditions.
- Loops: Use loops such as “for”, “while”, and “do-while” to execute code repeatedly.
- Functions: Use the “function” keyword to define a function. For example:
function addNumbers(x, y) { return x + y; }- Objects: Use objects to store data as key-value pairs. For example:
- e
var person = { name: "John", age: 30, isMarried: false }; - Arrays: Use arrays to store multiple values in a single variable. For example:
var fruits = ["apple", "banana", "orange"];- DOM manipulation: Use JavaScript to manipulate the Document Object Model (DOM) of a web page to dynamically change the content and style of elements on the page. For example:
document.getElementById("myButton").addEventListener("click", function() {
document.getElementById("myDiv").innerHTML = "Hello, world!";
document.getElementById("myDiv").style.backgroundColor = "blue";
});
