Jifunze Java kidogo kwa wale wanaoanza
Since their invention in the 1950s,
computers have revolutionized our daily lives! Calculating a route from a
website or a GPS, booking a train or plane ticket, or seeing and chatting with
friends on the other side of the world: all these actions are possible
thanks to computers.
Let's take the term
"computer" in its broadest sense, meaning a machine that can
perform arithmetic and logical operations. It could mean either a desktop or
laptop computer (PC, Mac), a computing server, or a mobile device like a tablet
or smartphone.
Nonetheless, a computer can
only perform a series of simple operations when instructed to do so. They
normally have no ability to learn, judge, or improvise. They simple do what
they're told to do! Their value comes from how they can quickly handle and
process huge amounts of information.
A computer often requires
human intervention. That's where programmers and developers come in! They
write programs that result in instructions to a computer.
A computer program (also called an
application or software) is usually comprised of one or more text files
containing commands in the form of code. This is why developers are also called
coders.
A programming language is a way to
give orders to a computer. It's a bit like a human language! Each
programming language has vocabulary (keywords that each play a
specific role) and grammar (rules defining how to write programs in that
language).
How
do you create programs?
Programming
languages
There are a large number of
programming languages, each adapted to different uses and with its own
syntax. However, there are similarities between the most popular
programming languages. For example, here's a simple program written in Python:
print("Hello")
You can also write the same thing in
PHP:
<?php
echo("Hello\n");
?>
Or even C#!
class
Program {
static void Main(string[] args) {
Console.WriteLine("Hello");
}
}
What about Java?
public
class Program {
public static void main(String[] args) {
System.out.println("Hello");
}
}
All these programs display
"Hello" through a different set of instructions.
Learn
to code
Programs
Except in very simple cases, you
don't create programs by writing source code directly. You'll first need
to think about the instructions you'll want to convey.
Take a concrete example from
everyday life: I want to make a burrito. What are the steps that will
enable me to achieve my goal?
Begin
Get out the rice cooker
Fill it with rice
Fill it with water
Cook the rice
Chop the vegetables
Stir-fry the vegetables
Taste-test the vegetables
If the veggies are good
Remove them from the stove
If the veggies aren't good
Add more pepper and spices
If the veggies aren't cooked enough
Keep stir-frying the veggies
Heat the tortilla
Add rice to tortilla
Add vegetables to tortilla
Roll tortilla
End
Mmmmmm!
You reach your goal by
combining a set of actions in a specific order.
There are different types of actions:
There are different types of actions:
- simple actions ("get out the rice cooker")
- conditional actions ("if the veggies are good")
- actions that are repeated ("keep stir-frying the veggies")
We used a simple writing style, not
a specific programming language. In fact, we just wrote what is called an
program. We can define a program as an ordered sequence of operations
for solving a given problem. A program breaks down a complex problem
into a series of simple operations.
The
role of the programmer
Writing programs that can reliable
perform expected tasks is a programmer's goal. A beginner can learn
to quickly create simple programs. Things get more complicated when
the program evolves and becomes more complex. It takes experience and a lot of
practice before you feel like you'll control this complexity! Once you have the
foundation, the only limit is your imagination!
Understand JavaScript
It's possible to learn
programming without using a real programming language if you just study logic,
but how boring is that? You should learn programming as a concept at the same
time as you learn a programming language so you can instantly put your logic
into practice.
This course uses JavaScript
as a learning language.
JavaScript logo
JavaScript
introduction
JavaScript is probably the
main web programming language. It was invented in 1995 by Brendan Eich, who at
the time worked for Netscape, which created the first popular web browser (Firefox's
ancestor).
JavaScript should not be confused
with Java, another language invented at the same time!
The idea was to create a simple
language to make web pages dynamic and interactive, since back then, pages were
very simple.
Yahoo's home page circa 1994
Web builders starting gradually
enriching their pages by adding JavaScript code. For the code to work, the
recipient web browser (the software used to surf the web) had to be able
to process JavaScript. This language has been progressively integrated
into all browsers, and now all browsers are able to handle it!
Because of the explosion of the
Web and the advent of the web 2.0 (based on rich, interactive pages),
JavaScript has become increasingly popular. Web browser designers have
optimized the execution speed of JavaScript, which means it's now a very
powerful language.
This led to the 2009 emergence of
the Node.js platform, which allows you to create JavaScript web
applications very quickly. Thanks to a service called MongoDB, JavaScript has
even entered the database world (software whose role is to store information).
Finally, the popularity of
smartphones and tablets with different systems (iOS, Android, Windows
Phone) has led to the emergence of so-called cross-platform development tools.
They allow you to write a single mobile application that's compatible with
these systems. These tools are almost always based on...JavaScript!
In short, JavaScript is
everywhere. Knowing it will open the doors of the web browser-side
programming (known as front-end development), server side development
(backend), and mobile development. Not bad for a language that's relatively
simple to access.
JavaScript
versioning
JavaScript was standardized in 1997
under the name ECMAScript. Since then, the language has undergone several
rounds of improvements to fix some awkwardness and support new features.
This course uses the current version
of JavaScript, called ES5, introduced in 2009. The newest version of the
language (SS6 / ES2015) will be interesting but is, at the time this
course was written, not well enough supported by web browsers.
Configure your work environment
Now that you've had a brief intro to
programming and JavaScript, it's time to get more concrete. To start
programming in the right conditions, you'll need a good working
environment.
Code
with JavaScript online
A simple and fast solution for
coding with JavaScript is to use an online "sandbox." These are
websites that allow you to write HTML/CSS/JavaScript code and see the
results immediately. The most famous are JSFiddle, JS Bin,
and CodePen (I
like CodePen)!

These sites are great for
experimenting with and sharing code. However, it's also great to set up your
own machine with a working development environment.
Code
with JavaScript on your computer
Choosing
a Web browser
A web browser is an application that
displays web pages. All modern computers, whether desktop, portable, or
mobile, probably feature a web browser. The most famous are Firefox, Chrome and Internet Explorer, but there are many.
This course uses Google
Chrome, the most popular browser on the web.
Google Chrome
Like all web browsers,
Chrome is able to execute JavaScript code. We will use it to test our
programs written in JavaScript. It has tools dedicated to web development which
we will use a lot in this course. Open up these tools by selecting View
> Developer > Developer Tools from the menu up top.
Developer tools (JavaScript console)
Choose
a text editor
As you learned, programming involves
writing code as text in a number of files. Any text editor (yes, even
Word) will allow you to create and modify text files. However, some are
much better than others for working with code. In this course, I
recommend using a simple text editor called Sublime Text.
Organize
your code
You're almost ready to get started!
It's important to set up your basic folder and file structure before actually
starting to code. That way, your project will be organized, and you'll be
starting off with some good programming habits! 
You can either create the project
files for this course from scratch or use the file skeleton I've already
created for you. Each chapter is set up in a series of folders as follows:
Course file structure
Each chapter has a folder, which
contains an html and a js folder, each of which contains a file. These files
are what you can fill out for each chapter, or you can create your examples on CodePen.
In your first JavaScript file
(chapter-1/js/course.js if you're using the file skeleton provided), type the
following content:
console.log("Hello
in JavaScript!");
The .js at the end of the name
indicates that the file contains JavaScript. All JavaScript files will have
this extension.
Add the following content in
the above file's HTML equivalent, chapter-1/html/course.html.
<!doctype
html>
<html>
<head>
<meta charset="utf-8">
<title>Introduction to
JavaScript</title>
</head>
<body>
<script
src="../js/course.js"></script>
</body>
</html>
Not sure what you just typed? Don't
worry! This is HTML, which uses tags like <title> or
<body> to describe the content of the page.
While copying/pasting is fastest, I
recommend manually typing all the sample code in the editor. You'll better
retain the language syntax.
HTML is not a programming language
but a content description language. Usually an HTML page contains many tags
that display information in a structured way, such as titles, images, links to
other pages, and more.
Our website is a bit special because
it contains no content that will be displayed by the browser. The purpose
of this page is to tell the browser that we want to execute JavaScript file
through the <script> tag.
You'll notice a file
path (src="../
js / course.js" ) in each example. We say that the
path "points" to this file. The path shown here is the file
located in the course.js chapter-1 / js directory. Two dots (.. ) at the beginning of the path
indicate you're going back one level in the directory structure relative
to the HTML file itself. When a web browser will attempt to display the course.html page, it will execute the JavaScript code in the file
course.js .
Again, you'll ultimately have the
folder structure below.
Your file structure
Try
out your first program
Once you open a web page in a
browser, the content will show in the main window, and the associated
JavaScript console will show up in the console below (assuming you have it
open).
Before opening your project in a
browser, make sure you save both the course.js and course.html files.
HTML opened in browser
Make sure you're opening course.html (the HTML document) in the browser -- not the .js one!
Otherwise, you'll get an error. 
If you get this same result in your
browser, two bits of great news for you:
- Your work environment is ready for the course.
- You've already written your first line of JavaScript!
1, 2, 3: code!
Let's get started! This chapter will
introduce you to the fundamentals of programming including values, types, and
program structure.
Values
and types
A value is a piece of information
used in a computer program. Values exist in different forms called types. The
type of a value determines its role and operations available to it.
Every computer language has its own
types and values. Let's look at two main types available in JavaScript.
Number
A number is a numerical value
(thanks Captain Obvious). Let's go beyond that though! Like mathematics, you
can use integer values (or whole numbers) such as 0, 1, 2, 3, etc, or real
numbers with decimals for greater accuracy.
Numbers are mainly used for
counting. The main operations you'll see are summarized in the following table.
|
Operator
|
Job
|
|
+
|
Addition
|
|
-
|
Subtraction
|
|
*
|
Multiplication
|
|
/
|
Division
|
Most browser consoles allow you to
type JavaScript code and execute it. In the Chrome console, simply type 8 * 4
and press Enter. You get the expected result: 32
. Test other operations!
Numbers in JavaScript
Strings
A string in JavaScript is text surrounded
quotation marks, such as "This is a string."
You can also define strings with a
pair of single quotes: 'This is a string.' The best practice for single or
double quotes is a whole political thing. Use whichever you like, but don't mix
the two!
Always remember to close a string
with the same type of quotation marks you started it with.
To include special characters in a
string, use the \ character (backslash) before the character. For
example, type \n to add a new line within in a string.
In your browser console, enter the
line "Helloooooo
string! \nMore lines here!"
(including the quotes). You'll get a two-line result.
Strings in JavaScript
You can not add or remove string
values like you'd do with numbers. However, the +
operator can be applied to two string values. This will join two
chains together, otherwise called concatenation.
In the browser console, type "Hey" + "
there." You get the result "Hey there."
String concatenation
If you get the result
"Heythere." it's because you didn't add a space either after the
string "Hey" or before "there."
Displaying
values
When you want to display a value
from a JavaScript program, use the JavaScript command console.log() . The value you want displayed is enclosed in parentheses
and followed by a semicolon. It could, for example, be a number or a string.
You might remember this from the course.js program you created in the previous chapter: it shows
"Hello in JavaScript", which is a string.
console.log
( "Hello in JavaScript!");
Displaying text on the screen (the
famous "Hello world") is often the first thing you'll do when you
learn programming. It's the classic example. You've already taken that first
step!
Program
structure
We already defined a computer
program as a list of commands telling a computer what to do. These orders are
written as text files and make up what's called the "source code" of
the program. The lines of text in a source code file are called lines of code.
The source code may include empty
lines: these will be ignored when the program executes.
Instructions
Each instruction inside in a program
is called a statement. A statement in JavaScript ends with a semicolon, and
your program will be made up of a series of these statements.
You usually write only one statement
per line.
Execution
flow
When a program is executed, the
instructions in it are "read" one after another. It's is the
combination of these individual results that produces the final result of the
program.
Hop back to Sublime and add the
contents below to your course.js file. The instructions in here will be read and
executed, line by line.
console.log("Hello
in JavaScript!");
console.log("Let's
do some math.");
console.log(4
+ 7);
console.log(12
/ 0);
console.log("Goodbye.");
Comments
By default, each line of text in the
source files of a program is considered a statement that should be
executed. You can prevent certain lines from executing by putting
a double slash before them: // . This turns the code into
a comment.
Modify course.js by adding // on several lines. You'll
notice the text grays out:
console.log("Hello
in JavaScript!");
//
console.log("Let's do some math.");
console.log(4
+ 7);
//
console.log(12 / 0);
console.log("Goodbye.");
Re-open your course.html file in Chrome, and you'll notice that the commented-out
lines no longer appear in the console. As we hoped, they weren't executed!
Comments are great for developers so
you can write comments to yourself, explanations about your code, and more,
without the computer actually executing any of it.
You can also write comments by
typing /*
*/ around the code you want commented
out.
/*
A comment
on
multiple
lines
*/
//
A comment on one line
Play with variables
You know how to use JavaScript to
display values. However, for a program to be truly useful, it must be able to
store data, like information entered by a user. Let's check that out.
Variables
Role
of a variable
A computer program stores data using
variables. A variable is an information storage area. We can imagine it as a
box in which you can put and store things!
Variable
properties
A variable has three properties:
- Its name, which identifies it. A variable name may contain upper and lower case letters, numbers (not in the first position, ex. 1stvariable ) and characters like the dollar ($) or underscore (_).
- Its value, which is the data stored in the variable.
- Its type, which determines the role and actions available to the variable.
You don't have to define a
variable type explicitly in JavaScript. Its type is deduced from the value
stored in the variable and may change while the program runs. That's why we say
that JavaScript is a dynamically typed language. Other languages,
like C or Java, require variable types to be defined. This is called static
typing.
Declaring
a variable
Before you can store information in
a variable, you have to create it! This is called declaring a variable.
Declaring a variable means the computer reserves memory in which to store the
variable. The program can then read or write data in this memory area by
manipulating the variable.
Here's a code example that declares
a variable and shows its contents:
var
a;
console.log(a);
In JavaScript, you declare a
variable with the var keyword followed by the variable name. In this
example, the variable created is called a .
Add the above code to your chapter-2 JavaScript file, and open it in Chrome. You'll see the
following:

Note that the result is undefined ! This is a JavaScript-type indicating no value. I
declared the variable, calling it a but didn't give it a value!
Assign values
to variables
While a program is running, the
value stored in a variable can change. To give new value to a variable, use the
= operator called an assignment operator.
Check out the example below:
var
a;
a
= 3.14;
console.log(a);
Here's what you'd get as a result.

We modified the variable by
assigning it a value. a =
3.14 reads as a
received the value 3.14 .
Be careful not to confuse the
assignment operator = with mathematical equality! You'll soon see how
to express equality in JavaScript.
You can also combine declaring a
variable and assigning it a value in one line. Just know that, within this
line 1, you're doing two different things at once:
var
a = 3.14;
console.log(a);
Increment
a number variable
You can also increase or
decrease a value of a number with += and ++
. The latter is called an increment operator, as it allows
incrementation (increase by 1) of a variable's value.
In the following example, lines 2
and 3 each increase the value of variable b by 1.
var
b = 0; // b contains 0
b
+= 1; // b contains 1
b++;
// b contains 2
console.log(b);
// show 2
Type
conversion
An expression's evaluation can
result in type conversion. These are called implicit conversions, as
they happen automatically without the programmer's intervention. For
example, using the + operator between a string and a number causes the
concatenation of two values into a result: a string.
var
f = 100;
console.log("The
variable f contains the value: " + f);

JavaScript is very tolerant in terms
of type conversion. However, sometimes conversion isn't possible. If a
number fails to convert, you'll get the result NaN
(Not a Number).
var
g = "five" * 2;
console.log(g);
// Shows NaN
Sometimes you'll wish to convert
the value of another type. This is called explicit conversion. JavaScript
has the Number() and String() commands for this that convert numbers and
strings.
var
h = "5";
console.log(h
+ 1); // Concatenation: shows the string "51"
h
= Number("5");
console.log(h
+ 1); // Addition: show the number 6
User
interactions
Entering
and displaying information
Once you start using variables, you
can write programs that exchange information with the user.
In the chapter-2 / js directory, create a file named hello.js with the contents below.
var
name = prompt ("Enter your first name:");
alert
("Hello, " + name);
In the chapter-2 / html
directory, create a hello.html file and point it toward hello.js . Open the page, and an alert will pop up asking
for your name.
This is
the result of the JavaScript command prompt("Enter your first name:").
Type your name and click okay.
You'll then get a personalized greeting.

The value you entered in the first
dialog box has been stored as a string in the variable name
. The JavaScript command alert() then triggered the display of the second box,
containing the result of the concatenation of the string "Hello, " with the value of the name variable.
Naming
variables
To close this chapter, let's discuss
variable naming conventions. The computer doesn't care about variable names.
You could name your variables using the classic example of a single letter
(a, b, c...) or choose absurd names like burrito or puppieskittens90210 .
Nonetheless, naming variables
well can make your code much easier to read. Check out these two
examples:
var
nb1 = 5.5;
var
nb2 = 3.14;
var
nb3 = 2 * nb2 * nb1;
console.log(nb3);
var
radius = 5.5;
var
pi = 3.14;
var
diameter = 2 * pi * radius;
console.log(diameter);
They function in the same way, but
the second version is much easier to understand. How are some good ways to
name variables?
Choose
meaningful names
The most important rule is to give
each variable a name that reflects its role. This is the case in the second
example above, where you use the word radius to actually indicate...well, a
radius.
Don't
use reserved words
The keywords of JavaScript are
reserved names. They should not be used as variable names. Here's the list of
reserved words in JavaScript.
Follow
a convention
It can take several words to
describe the roles of certain variables. The most common way to account
for these variables is to use camelCase, based on two main principles:
- All variable names begin with a lowercase letter.
- If the name of a variable consists of several words, the first letter of each word (except the first word) is uppercase.
Like many languages, JavaScript is
case sensitive. For example, myVariable and myvariable are two different
variable names. Be careful!
Add conditions
Up until now, all the code in our
programs has been executed chronologically. Let's enrich our code by
adding conditional execution!
What's
a condition?
Suppose we want to write a program
that makes enter a number to the user, who then displays a message if the
number is positive. Here the corresponding algorithm.
Enter
a number
If
the number is positive
Display Message
The message should display only
if the number is positive: this means it's "subject" to a condition.
The
if statement
Here's how you translate
the program to JavaScript.
var
number = Number (prompt("Enter a number:"));
if
(number > 0) {
console.log (number + " is
positive");
}
Most basically, conditional syntax
looks like this:
if
(condition) {
// Statements executed when the condition
is true
}
The pair of opening and closing
braces defines what is called a block of code associated with anif statement.
This statement represents a test. It can result in the following: "If the
condition is true, then executes the instructions contained in the code
block."
The condition is always placed in
parentheses after theif.
The statements within the
associated code block are shifted to the right. This practice is called indentation
and helps make your code more readable.
Conditions
A condition is an expression that
evaluates whether something is true or false. When the value of a
condition is true, we say that this condition is satisfied.
We have already studied numbers and
strings, two types of data in JavaScript. Booleans are another
type. This type has two possible values: true and false.
Any expression producing a Boolean
value (either true or false) can be used as a condition in anif statement.
If the value of this expression is true, the code block associated with
it is executed.
Boolean expressions can be created
using the comparison operators shown in the following table.
|
Operator
|
Meaning
|
|
===
|
Equal to
|
|
!==
|
Not equal to
|
|
<
|
Less than
|
|
<=
|
Less than or equal to
|
|
>
|
Greater than
|
|
>=
|
Greater or equal to
|
It's easy to confuse comparison
operators like === (or ==) with the assignment operator
( = ). They're very, very different. Be warned!
In yourchapter-3 directory, modify the following code to
replace > with >= and change the message, then
test it with the number 0.
var
number = Number(prompt("Enter a number:"));
if
(number >= 0) {
console.log(number + " is positive or
zero.");
}

The message appears in the console,
which means that the condition(number
>= 0) was true!
Alternative
conditions
You'll often want to have your code
execute one way when something's true and another way when something's false.
Else
Let's enrich our sample with
different messages depending if the number's positive or not.
var
number = Number(prompt("Enter a number:"));
if
(number > 0) {
console.log(number + " is
positive");
}
else
{
console.log(number + " is negative or
zero");
}
Test this code with a positive
number, negative number, and zero, while watching the result in the console.
The code executes differently depending if the statement (number > 0) is true or false.
To make this happen, use the
keyword else along with an initial if:
if
(condition) {
// code to run when condition is true
}
else
{
// code to run when condition is not true
}
You can translate an if / else
statement like this: "If the condition is true, then execute this first
set of code; otherwise, execute this next set of code.
Nesting
conditions
You can go next level and
display a specific message if the entered number is zero. Use else if for a second conditional. See this example, which has a
positive test case, negative test case, and a last resort of the number being
zero:
var
number = Number(prompt("Enter a number:"));
if
(number > 0) {
console.log(number + " is
positive");
}
else if (number < 0) {
console.log(number + " is
negative");
}
else {
console.log(number + " is zero");
}
Add
additional logic
"And"
operator
Suppose you want to check if a
number is between 0 and 100. You're essentially checking if
it's "greater than or equal to 0" and "less than or
equal to 100."
Here's how you'd translate that same
check into JS.
if
((number >= 0) && (number <= 100)) {
console.log(number + " is between 0
and 100, both included");
}
The && operator (and) can apply to both types of boolean
values. true will only be the result of the statement if both
conditions are true.
console.log(true
&& true); // true
console.log(true
&& false); // false
console.log(false
&& true); // false
console.log(false
&& false); // false
"Or"
operator
Now imagine you want to check that a
number is outside the range of 0 and 100. To meet this requirement, the number
should be less than 0 or greater than 100.
Here it is, translated into
JavaScript:
if
((number < 0) || (number > 100)) {
console.log(number + "is not in
between 0 and 100");
}
The || operator
("or") makes statements true if at least one of the
statements is true. For example:
console.log(true
|| true); // true
console.log(true
|| false); // true
console.log(false
|| true); // true
console.log(false
|| false); // false
"Not"
operator
There's another operator for when
you know what you don't want: the not operator! You'll use a !
for this.
if
(!(number > 100)) {
console.log(number + " is less than or
equal to 100");
}
Therefore:
console.log(!true);
// false
console.log(!false);
// true
Wild, right?!

Multiple
choices
Let's write some code that helps
people decide what to wear based on the weather using if/else.
var
weather = prompt("What's the weather like?");
if
(weather === "sunny") {
console.log("T-shirt time!");
}
else if (weather === "windy") {
console.log("Windbreaker life.");
}
else if (weather === "rainy") {
console.log("Bring that
umbrella!");
}
else if (weather === "snowy") {
console.log("Just stay inside!");
}
else {
console.log("Not a valid weather
type");
}
Add this code in the course.js file and test it out.
When a program should trigger a
block from several operations depending on the value of an expression, you can
write it using the JavaScript statement switch to do the same thing.
var
weather = prompt("What's the weather like?");
switch
(weather) {
case
"sunny":
console.log("T-shirt time!");
break;
case
"windy":
console.log("Windbreaker life.");
break;
case
"rainy":
console.log("Bring that
umbrella!");
break;
case
"snowy":
console.log("Just stay inside!");
break;
default:
console.log("Not a valid weather
type");
}
If you test it out, the result will
be the same as the previous version.
The wordswitch kicks
off the execution of one code block among many. Only the code block
that matches the relevant situation will be executed.
switch
(expression) {
case
value1:
// code when the expression matches value1
break;
case
value2:
// code when the expression matches value2
break;
...
default:
// code for when neither case matches
}
You can set as many cases as you
want! The word default, which is put at the end of switch,
is optional. It can let you handle errors or unexpected values.
break; in each block is important so you get out of
the switch statement
Comments
Post a Comment
solate forever