JavaScript is a popular programming language which originated as the standard way web browsers add interactivity to an otherwise static web page.
Throughout this tutorial you will learn about some of the basics JavaScript.
Some slides will have examples of JavaScript code with an explanation of what's being demonstrated.
function myFunc(){
return 'I am some JavaScript code!';
}
For example, the above code will create a function that returns a string.
Other slides will allow you to edit and then run code to see what the resulting output is.
console.log("I can count to ten!");
for(var i=1; i<11; i++){
console.log(i);
}
There will also be problems to solve which will give you feedback if your code doesn't produce the right output.
var score = 76;
console.log(score > 80 ? "You passed" : "You failed");
Some problems will be more complex, requiring a function to be defined that satisfies a number of test cases.
function sumAllNumbers(){
return Array.prototype.slice.call(arguments).reduce(function(p,n){
return p+n;
});
}
Test case | Expected result | Outcome |
---|---|---|
sumAllNumbers(1,2,3) | 6 | |
sumAllNumbers(2,3) | 5 | |
sumAllNumbers(56,44,100,300) | 500 |
For example, there might be some further explanations about the code or links to helpful resources.
In JavaScript, the program is simple; just one line.
Try running the program to see the result. You can edit the Hello World! text to display any message you like.
console.log("Hello World!");
Great job on running your first program!
console.log("Hello World!");
There are a few of things to understand from this really simple first program:
To define a variable in JavaScript you use the var keyword followed by the variable name and then a value is assigned to it by using an equals sign.
var myName = "James";
var myPassword;
var myAge = 21;
All three examples above are correct ways of defining variables.
You might notice that the myPassword variable doesn't have a value assigned to it. That's OK, it will just be assigned the special value of undefined until you give it a value.
Don't forget: a string of letters must be enclosed in double quotes.
When you want to use a variable, you simply reference it's name in another part of your program.
var age = 21;
console.log("You are " + age + " years old");
age = 22;
Define a variable called myName in the code example below. When you run the code, you will see a customised greeting being displayed!
// Define your variable here
// This outputs the value of your variable
console.log("Hi " + myName + "! pleased to meet you!");
A project for juniordevelopercentral.com