This tutorial aims to introduce you to the fundamental concepts of JavaScript, a versatile and powerful programming language used extensively in web development to create interactive web pages.
By the end of this tutorial, you'll have a solid understanding of JavaScript's basic structure and syntax, and you'll know how to embed JavaScript code into your HTML files.
Prerequisites: Basic understanding of HTML and CSS would be helpful but not necessary.
JavaScript is a high-level, interpreted programming language. It's one of the three core technologies of web production, alongside HTML and CSS. While HTML and CSS take care of the content and styling, JavaScript is responsible for a webpage's interactivity.
A typical JavaScript code snippet consists of statements, variables, operators, comments, and control structures.
Example:
var x = 10; // This is a JavaScript statement
var
keyword is used for variable declaration.Example:
var x; // Declares a variable named x
x = 5; // Assigns the value 5 to x
+
, -
, *
, /
) to compute values.Example:
var x = 10 + 5; // x will be 15
Example:
// This is a single line comment
/* This is a
multi-line
comment */
if
, else
, for
, while
, etc., are used to control the flow of the program.Example:
if (x > 0) {
console.log(x + " is positive");
} else {
console.log(x + " is negative or zero");
}
JavaScript code can be included in an HTML file in two ways:
<script>
tag in the HTML file.<script>
alert("Hello, World!");
</script>
.js
file.<script src="script.js"></script>
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<button type="button" onclick="alert('Hello, World!')">Click Me!</button>
</body>
</html>
This code creates an HTML button. When clicked, it triggers a JavaScript function (alert()
) that displays an alert box with the message 'Hello, World!'
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">This is a demonstration.</p>
<button type="button" onclick="document.getElementById('demo').innerHTML = 'Hello, JavaScript!'">Click Me!</button>
</body>
</html>
This code creates an HTML button. When clicked, it triggers a JavaScript function that changes the content of the HTML element with id 'demo' to 'Hello, JavaScript!'
In this tutorial, we've learned the basics of JavaScript, including its role in web development, its syntax and structure, and how to include JavaScript in HTML files.
As your next steps, consider learning more about JavaScript functions, objects, events, and error handling.
var currentDate = new Date();
console.log(currentDate);
function reverseString(str) {
return str.split("").reverse().join("");
}
console.log(reverseString("Hello, World!")); // Outputs "!dlroW ,olleH"
var numbers = [5, 2, 8, 1, 4];
numbers.sort(function(a, b){return a-b});
console.log(numbers); // Outputs [1, 2, 4, 5, 8]
Remember, the best way to learn programming is by doing. Practice and patience are key. Happy coding!