I have a confession. JavaScript and I started badly. My first foray was for form validation. I would cuss about its existence.
As luck would have after being reintroduced to it I began to respect it. Over the years it has grown into a powerful language.
JavaScript
With its humble beginnings, JavaScript has evolved into a modern programming language. From the browser to the server it can handle almost everything. Node.js gives it a powerful framework on the server side.
Mozilla created it and here is how they define it. “JavaScript is a lightweight interpreted programming language with first-class functions.” That is a mouthful!
Code
Let’s look at some basic code. It is an HTML file displaying some JavaScript. Save this code to your local machine.
<!DOCTYPE html>
<head>
<title>JavaScript example code</title>
<style>
</style>
</head>
<body>
<script>
alert("JavaScript is working!")
</script>
<h1>Test 1</h1>
<h2>Test 2</h2>
Regular text
</body>
When we run this we will see this.
Once you click ok you will see this.
Statement
The statement is the basic instruction for JavaScript. We can create some variables and then assign them values.
let a, b, c; // Statement creating three variables
a = 2; // Statement assign the value of 2 to variable a
b = 3; // Statement assign the value of 3 to variable b
c = a + b; // Statement assign a plus b to c
The semicolon is at the end of the statement. Although we could put multiple statements together.
a = 2; b = 3;
This isn’t as readable so most programmers prefer not to. So just because you can do something doesn't mean you should.
Functions
When we want to perform a task we can create a function. If we need to sum two numbers we could do this in code or create a function.
// Add two numbers
num3 = num1 + num2;
// Function to sum two numbers
function sumTwoNumbers(num1, num2) {
return num1 + num2;
}
In this example, we perform the same code one in a function and one not. Using a function has value. We can call it repeatedly. Also, we could easily add some error checking too.
// Function to sum two numbers
function sumTwoNumbers(num1, num2) {
return num1 + num2;
}
let sum = sumTwoNumbers(6,4);
If you want to call the function we can do it like this example. Here we pass in two numbers. These numbers could be replaced with variables as well.
In closing, we have touched on why we would use JavaScript. Then we started to code. Using statements and functions we started to see what is under the hood. Try it out for yourself! You won’t regret it.