JavaScript
is a Scripting Language
A scripting language is a
lightweight programming language.
JavaScript is programming code that
can be inserted into HTML pages.
Scripts in HTML must be inserted between tags.
Scripts can be put in the and in the
section of an HTML page.
alert("My First JavaScript");
How to use in body :-
.
.
document.write("
This is a heading
");document.write("
This is a paragraph
");.
.
Document.write ka matlab hai ki html page mein kuch bhi likhna .
Javascript in head:-
My Web Page
A Paragraph
Javascript in body:-
My Web Page
A Paragraph
Button
jispar click karney se alert box khuley :-
The alert() function is not much used in JavaScript, but it is often quite handy for trying out code.
The onclick event is only one of the many HTML events you will learn about in this tutorial.
My First JavaScript
JavaScript can
change the content of an HTML element.
function myFunction()
{
x=document.getElementById("demo"); // Find the element
x.innerHTML="Hello JavaScript!"; // Change the content
(agar yahan par x.style=”red”) // to color change ho jayega
}
Output:
My First JavaScript
JavaScript can change the content of an HTML element.
Ek
button
Jis
par click karney se text chage ho jayega aur ban jayega hello javascript
Another
example:-
function changeImage()
{
element=document.getElementById('myimage')
if (element.src.match("bulbon"))
{
element.src="pic_bulboff.gif";
}
else
{
element.src="pic_bulbon.gif";
}
}
src="pic_bulboff.gif"
width="100" height="180">
Click
the light bulb to turn on/off the light
Output
–
Ek
bulb hai jis par click karney se pics change hoti hai ……server got 2 pics one
bulb on wali and off wali
Example
:-
My First JavaScript
Please
input a number.
function myFunction()
{
var x=document.getElementById("demo").value;
if(x==""||isNaN(x))
{
alert("Not Numeric");
}
}
Output:-
Ek
input text area hhai aur sath mein ek button click karney par batata hai agar
hum ismey abcd likhdey …..alert box khulkey batata hai .
Javascript
:-
Create a variable called myName and set it to a
string containing your name. Then type myName and press Enter to see what the
variable myName stores.
var myName="viveck"
myName
=> 'viveck'
Replace the blanks with the correct variable names in the following code: "My name is " + ____ + " and I am learning " + ____;
"My name is " + myName + " and I am learning " + favoriteLanguage;
'My name is viveck and I am learning JavaScript'
'My name is viveck and I am learning JavaScript'
Try creating a variable calledmyAge
that stores your age. Then typemyAge
and press Enter to see its value.
myAge=23;
=> 23
Try setting myAge
to a string that spells out your current age.
myAge="twenty two";
=> 'twenty two'
Try checking if the variablesalicesAge
andbobsAge
have the same values using the equality operator.
alicesAge == bobsAge
=> false
That returnedfalse
because Alice is 19 and Bob is 20. If they were the same age, your code would have evaluated totrue
. We've covered a few operators already, but check out some other commonly used operators in the description.
We've seen that variables have values, but did you know they also have types? The type of a variable is essentially the data type (e.g. string, number, etc.) that the variable stores. So how do we know if a variable stores a number or a string? We can use the handytypeof
operator to figure it out. We've created a variable for you calledsecret
that contains -- you guessed it -- a secret value. Can you figure out its type? Give it a try!
typeof secret
=> 'number'
Empty Cans, Empty Variables
Sometimes you might want to create a variable for later use, but don't know the value you want to assign to it just yet. JS lets you declare variables without assigning a specific value. In this case, the variable will have an"undefined"
value. You can do this by declaring a variable and leaving out the assignment operator and any value. Try creating an undefined variable calledemptyCan
. Then check the type of the variable using the appropriate operator.
typeof emptyCan;
=> 'undefined'
Now that you have an empty variable, you can assign a value to it later.
Increment Operator
Now you know how to create and change variables. A common task in programming is incrementing the value of a variable, like we did when we increased themyAge
variable by one. This is such a common task that there's a special operator for it in JS, the++
, or increment, operator. Increment the value of the variable calledcounter
which we have already created for you. Then type the variable namecounter
and press Enter to see its updated value.
counter++;
=> 0
Awesome! The increment operator will be handy when you're writing a lot of code. There is also a similar decrement operator, --
, which is used to decrease the value of a variable by one.
12Adding Numbers, Again
What if you wanted to increment the value of a variable by any number, not just one? There is a way to do this using the assignment operator. For example, if you want to increase the value of a variablex
by 10, you can use the codex = x + 10;
.
This works because the code on the right hand side of the assignment operator is evaluated first, then the resulting value is assigned to the variablex
. So JS evaluatesx + 10
and then reassigns the result to the variablex
.
Increment the value of the variable counter
by 5.
counter=counter+5;
=> 6
You can also subtract any number from a variable similarly, by using the-
operator instead of the+
operator.
Another Addition Operator
Adding numbers to variables is such a common task in programming that there is a special operator for it. The+=
operator is short hand for incrementing a variable by a number. For example, instead ofx = x + 10;
, you can writex += 10;
. They both do the same thing.
Use this operator to increment the variable counter
by itself.
counter += counter;
=> 42
Length of a String
Remember that a string is a sequence of characters. The length of a string is the number of characters in it. Every string in JS has alength
property which stores the number of characters in the string. For example,"keep it up".length
will evaluate to 10 (remember, spaces are characters too).
Get the length of the string stored in the variable ls
.
ls.length;
=> 11
Selecting Characters important
Imagine that you have a list of strings containing words and you want to sort them alphabetically. You'll need a way to get the first character in each string. You might even need the second or third character if there are multiple words with the same first letter.
The charAt(index)
is a handy way to get the character at a specific position in a string. Keep in mind that strings are zero-indexed, meaning the first position is position 0, the next one is position 1, and the last one is position length - 1.
For example, we can get the character at position2
in the string"hello"
by doing"hello".charAt(2)
.
What is the last character in the string stored in the variable ls
?
ls.charAt(ls.length - 1);
=> 't'
Good Job!
5Substrings
Easy hai samjho isko ab :-
Suppose ek string hai hamarey pass “universityofengland” if u need the output of first 5 characters then we can use substring
“universityofengland”.substring(0,4) here o is starting index and 4 is end index……….. substring index from 0 remember and it wont include last string and gieves ur output first 5 characters
Okk that’s it is easy
And this will return
and "LearnStreet".substring(5);
returns "Street"
to find character in a string :-
indexOf(value)
returns the the first index of the specified character or string. Example:"LearnStreet".indexOf("e");
returns 1 because the letter 'e' first occurs at index 1.
It's great that we can get one character usingcharAt(index)
, but what if we wanted to get a longer part of a string? A contiguous part of a string is called a substring. Thesubstring(start, end)
function gives us a substring starting at thestart
index and going up to but not including theend
index.
Use thesubstring(start, end)
function to select the first word in the string stored in the variablemessage
.message
stores the string"Hello World"
.
message.substring(0, 5);
=> 'Hello'
Change to Upper Case
It's time to get angry and yell at people on the Internet! Just joking ;) Instead of holding down the Shift key or using Caps Lock, let's try to code something to do it. We can use the toUpperCase()
function to do this.
Take the stringmessage
and return an upper case version of it. Update themessage
variable with the upper case version of it.
message.toUpperCase();
=> 'I USED TO BE LOWERCASE BUT NOW I AM UPPERCASE'
What is your Index?
What if you wanted to check if a string contains a particular character or substring? One way to do this is using theindexOf(value)
function. This function takes a character or string and returns the first index at which it occurs. For example,"the big bang".indexOf("big")
returns 4 because "big" starts at index 4. When the character or string provided is not present, this function returns -1.
We received an email from an unknown source. The content of the email is stored in the variable message
. The way our email application works is if the message contains the word "free", it goes to our spam folder. Find out if the message should go to our spam folder. If the email is spam (e.g. contains "free"), your expression should evaluate to true and otherwise evaluate to false.
message.indexOf("free") != -1;
=> false
Nice! That should take care of most of the spam we get.
Reversing a String
Now that we've covered some commonly used string helper functions, let's try to do something a little harder. We're going to give you a string and you're going to return the reverse of the string. For example, if we give you"gum"
, you will return"mug"
.
How do you do this? Remember that we can use the+
operator to combine two strings together, and we can use thecharAt(index)
function to get the character at a given index.
The variablemessage
contains a three letter word. What is the reverse of the string stored inmessage
?
message.charAt(2) + message.charAt(1) + message.charAt(0)
=> 'hey'
What's the Secret?
Your friend wants to text you a secret message. But she doesn't want to send it in one text, in case your arch nemesis gets hold of your phone. Instead of just sending the secret message in one text, she's going to split up her secret and send you two messages. The first half of the first message combined with the second half of the second message will give you the full secret message.
The first message is stored inmessage1
and the second message inmessage2
Figure out what the full secret message is, using what you've learned so far.
message1.substring(0, message1.length / 2) + message2.substring(message2.length / 2, message2.length)
=> 'i ate your cookie'
*Write
the function body below to return a string that is
identical to str except that its first
letter is capitalized.*/
function capitalizeFirst(str) {
return str.charAt(0).toUpperCase() +
str.substring(1, str.length);
}
You're building a website and you want
to store everyone's names with correct capitalization. People use all sorts of
capitalizations when they enter their first and last name, like "jOhn
SMIth", "anne doe", and "david Shi", for example. You
want to store names so that only the first letter of the first name and first
letter of the last name are capitalized, like "Amy Sue".
In the code editor, complete the function called
In the code editor, complete the function called
capitalizeName
that takes a string containing someone's full name, with their first name and
last name separated by a space like "bOb dyLan", and returns the
correctly capitalized name, like "Bob Dylan". We've already started
it for you by converting the name to lower case. It will be useful to use the capitalizeFirst
function which you coded in the previous exercise.function capitalizeFirst(str) {
return
str.charAt(0).toUpperCase() + str.substring(1, str.length);
}
function capitalizeName(name){
var lowerName =
name.toLowerCase();
var spaceIndex =
lowerName.indexOf(' ');
var first =
lowerName.substring(0, spaceIndex)
var last =
lowerName.substring(spaceIndex + 1, lowerName.length);
return
capitalizeFirst(first) + ' ' + capitalizeFirst(last);
}
Let's do some more practice with
functions. Write a function called
square
that takes a
number and returns the square of that number.function square(num) {
return num * num;
}
Let's write a function that might be
useful if you have geometry homework. Code a function called
triangleArea
that takes two numbers -- base
and height
-- and returns the area of a triangle with the given base and height. The
formula for the area of a triangle is (1/2) * base * height.function triangleArea(base, height) {
return 0.5 * base *
height;
}
Now we are going to code a function that
says 'hello' to you. Code a function called
hello
that takes in one argument, your name, and returns the string "Hello,
" followed by your name.function hello(name) {
return "Hello,
" + name;
}
In this exercise, we won't be returning
a value. We are instead modifying a global variable, x. Write the function
incrementX
that increments the variable x
by amount
.
var
x = 10;
function
incrementX(amount) {
//Write code to increment x by amount. Don't
return anything.
function incrementX(amount) {
x += amount;
}
}
Authenticate
program:-
function authenticate(password) {
var
successMessage = "you are now logged in!";
var
failureMessage = "oops. try again.";
if
(password == "jsrocks") {
return successMessage;
} else {
return failureMessage;
}
}
Write a function called
authChuckNorris
that takes a username and a password and returns a success message only if the
username is "chuck"
and the
password is "norris"
. Otherwise
it returns an authentication failure message.function authChuckNorris(username,
password) {
var successMessage
= "welcome chuck norris!";
var failureMessage
= "sorry, try again.";
if
(username=="chuck" && password=="norris"){
return
successMessage;
}
else{
return
failureMessage;
}
}
Write a function named
find42
that takes two numbers and returns true
if either one is
42, their sum is 42, or their difference is 42. If any of those conditions
hold, the function should return true
. Otherwise it
should return false
. Remember that the
difference of two numbers a
and b
can be a
-b
or b
-a
.function find42(a, b) {
return a==42 ||
b==42 || (a+b)==42 || (a-b)==42 || (b-a)==42
}
A palindrome is a word that reads the
same forwards and backwards. For example, "civic" is a palindrome.
Write a function called
fivePalindrome
that
takes a string as an argument and checks if it is a 5 letter long palindrome.
Return true if it is, and false if it isn't. First check if it is 5 letters
long, and if it is, check if it's a palindrome. You can check if it's a
palindrome by comparing the letters at positions 0 & 4 and 1 & 3.
Function fivePalindrome(word) {
if (word.length == 5) {
return word.charAt(0) == word.charAt(4) && word.charAt(1) == word.charAt(3);
}else {
return false;
}
}
if (word.length == 5) {
return word.charAt(0) == word.charAt(4) && word.charAt(1) == word.charAt(3);
}else {
return false;
}
}
This is a slight modification of a
popular programming interview question. Write a function called
fizzBuzz
that takes a number and does the following: if the number is a multiple of 3
but not 5, return "Fizz"
; if the
number is a multiple of 5 but not 3, return "Buzz"
;
and if the number is a multiple of both 3 and 5, return "FizzBuzz"
.
If the number doesn't meet any of these conditions, just return the number
itself. Use the isMultipleOf(firstNumber, secondNumber)
function we've coded for you in the code editor to check if a number (firstNumber
)
is a multiple of another number (secondNumber
). It
returns true if it is a multiple, and false otherwise.function isMultipleOf(firstNum, secondNum)
{
return firstNum %
secondNum == 0;
}
function fizzBuzz(num) {
if
(isMultipleOf(num, 15)) {
return "FizzBuzz";
} else if (isMultipleOf(num,
5)) {
return "Buzz";
} else if
(isMultipleOf(num, 3)) {
return "Fizz";
} else {
return num;
}
}
You don't like waking up every morning
and thinking about how you're going to spend your day. As as result, you write
a program that tells you what to do.
Write a function called
Use the
Write a function called
decide
that takes a
string containing the day of the week and another string containing the
weather, and returns a string telling you how to spend your day. If it is a
weekday, return "go to work or school". If it's a weekend, check if
it's "rainy"
or if it is
"sunny"
. If it's
sunny, return "go outside" and it if it's raining, return "go
code". Use the
isWeekday(day)
function to
check if it is a weekday or weekend.function isWeekday(day) {
return day ==
"Monday" || day == "Tuesday" || day ==
"Wednesday" || day == "Thursday" || day ==
"Friday";
}
function decide(day, weather) {
var weekdayPlan =
"go to school or work";
var rainyWeekend =
"go code";
var sunnyWeekend =
"go outside";
//Complete the
function body below to return an activity depending on the day and weather.
if
(isWeekday(day)) {
return weekdayPlan;
} else {
if (weather == "sunny") {
return sunnyWeekend;
} else {
return rainyWeekend;
}
}
}
Arrays Introduction: An array is a
datatype that can hold more than one value (known as elements) at the same
time. This is especially useful if you want to group similar things together
and go through them at the same time with a loop. You can think of an array
like as a list of some objects, perhaps a shopping list and what you want to
buy. An example would be: var shoppingList = ["apple",
"banana", "kiwis", "mangos"];
Notice how we just made an object
with 4 strings in it separated by commas. The variable shoppingList now holds
all the fruits in one structure. Now that we have them all in one place, we
also need to have a way to select them from the array. The great thing about
arrays is that each element in the array has its own ID, so selecting is easy.
Selecting can be done by doing something like this: shoppingList[0]. This will
get the 0th element (array indices start at 0), which in this case is
"apple". Doing shoppingList[1] will get "banana" and doing
shoppingList[3] will get "mangos".
Array Methods: It is important to
know some methods that arrays utilize to aid your programming. Among those
include the following: sort() - sorts the array in its natural order (by number
increasingly, by alphabetical order). Example: var x = [3, 1, 4, 1, 5, 9, 2, 6,
5, 3, 5]; x.sort(); x is now [1, 1, 2, 3, 3, 5, 5, 6, 9] concat(array, ...) -
Combines all the arrays in the parameters into the original array Example: var
x = [1,2,3,4]; var y = [5, 6, 7]; var z = [8, 9, 10]; x.concat(y, z); x is now
[1,2,3,4,5,6,7,8,9,10] reverse() - Reverse the ordering of the array. var x =
[1,2,3]; x.reverse(); x is now [3,2,1];
Selecting Certain Parts of Arrays:
To select certain parts of array, but not just one element is possible in
JavaScript as well. The method that is already pre-written is called slice. The
syntax for it is slice(start, end) just like in substring for strings. It
starts from position start and ends before the end index. var x = [1,2,3,4,5];
and x.slice(2,4) would return [3,4].
Adding Elements Into Arrays It is
possible to add to arrays even after arrays are defined. This is done by using
the push or unshift functions of arrays.
Sometimes you want to add to the end
of an array. Then you would use the push function. For example you have an
array: var x = [1,2,3,4]; and you want to insert 5 into the end of the array.
In order to accomplish this, you would type x.push(5); to add 5 to the end of
the array. Most of the time inserting at the end of the array will suffice.
Still, occasionally it may be needed
to insert an element at the front of the array. This is when you would use
unshift, which inserts an element as you wanted it to. Doing x.unshift(0); on
the previous array will change the array to [0, 1, 2, 3, 4, 5]; assuming 5 was
pushed before.
Deleting Elements To remove the
first or last element, the methods to use are shift and pop respectively. An
example of how to use them is by taking the previous example: var x =
[1,2,3,4,5]; and doing x.pop(); which will remove the 5. After that if
x.shift() is called, then 1 would be removed leaving the array with only
[2,3,4].
Create an array that stores all the
numbers from 1 to 100 in increasing order.
var arr = [];
for (var i=1; i<=100; i++) {
arr.push(i);
}
Write a function
everyOther
that takes an array and adds up every other element (starting from the first
one) and returns the sum.function everyOther(arr) {
var sum = 0;
for (var i=0; i
< arr.length; i += 2) {
sum += arr[i];
}
return sum;
}
Write a function named
firstAndLast
that takes in an array and checks if the first element and the last element in
the array are equal.function firstAndLast(arr) {
return (arr[0] ==
arr[arr.length - 1]);
}
Notice that we did not need to use a
loop here because we knew exactly which two positions in the array we needed to
access in order to do the comparison.
Write a function called
reverse
that reverses the order of the elements in a given array. You can do this by
creating another function that swaps the order of two elements. For each
function, make sure to return the final result.function reverse(arr) {
for(i=0;
i
swap(arr,i,arr.length-
1 - i);
}
return arr;
}
function swap(arr, pos1, pos2) {
temp = arr[pos2];
arr[pos2]=arr[pos1];
arr[pos1]=temp;
}
As we did in this exercise, it can be
useful to create a "helper" method (like swap here) to make your code
easier to read.
Write a function called range that takes
a positive number and returns an array that contains all the numbers from 0 up
to and including the number.
function range(n) {
var nums = [];
for (var i = 0; i
<= n; i++) {
nums.push(i);
}
return nums;
}
Create an array with the numbers one
through five, spelled out in words. Remember to put quotes around them as
they're strings.
var arr = ["one",
"two", "three", "four", "five"];
Write a function called
iff
that takes an array and an item, and only adds the item to the end of the array
if the item is a string AND the array contains the number 6. Make sure to
return the resulting array (even if unchanged).function iff(arr, item) {
var isThere;
if (typeof
item=="string") {
isThere = "no";
for(i=0; i<=arr.length; i++) {
if (arr[i] == 6) {
isThere = "yes";
}
}
}
if (isThere ==
"yes") {
arr.push(item);
}
return arr;
}
No comments:
Post a Comment