Javascript beginners guide
Introduction
JavaScript is a programming language primarily used for web development to make web pages interactive. It seamlessly integrates with HTML and CSS to produce dynamic web content.
Variables
In JavaScript, variables are used to store data values. You can declare a variable using the 'var' keyword.
var x = 5;
var y = 6;
var z = x + y;
Data Types
JavaScript has different data types such as Number, String, Boolean, Object, and Undefined.
var num = 42; // Number
var str = 'Hello'; // String
var bool = true; // Boolean
var obj = {name: 'John', age: 30}; // Object
var notDefined; // Undefined
Functions
Functions in JavaScript are blocks of reusable code. They can be defined using the 'function' keyword.
function myFunction(p1, p2) {
return p1 * p2;
}
Conditions and Loops
JavaScript supports conditional statements like if, else if, and else. Loops like for and while are also supported to execute code multiple times based on a condition.
if (x > y) {
console.log('x is greater');
} else {
console.log('y is greater');
}
DOM Manipulation
The Document Object Model (DOM) represents the structure of an HTML document. With JavaScript, you can manipulate the DOM to change content, structure, and styles of a web page.
document.getElementById('myElement').innerText = 'New Content';
Events
Events are actions that can be detected by JavaScript, like a button being clicked. JavaScript can execute code in response to these events.
document.getElementById('myButton').addEventListener('click', function() {
alert('Button was clicked!');
});