From 72d9269efc0604b01989652335cf9f114709dfcd Mon Sep 17 00:00:00 2001 From: shivam8800 Date: Tue, 5 Sep 2017 01:41:42 +0530 Subject: [PATCH 01/22] translate first pharagraph of chapter -5 --- 01_values.txt | 850 +++++++++++------------------ 02_program_structure.txt | 1098 ++++++++++---------------------------- 04_data.txt | 1 - 05_higher_order.txt | 45 +- 07_elife.txt | 53 +- 5 files changed, 645 insertions(+), 1402 deletions(-) diff --git a/01_values.txt b/01_values.txt index 97c7d442d..f5671c268 100644 --- a/01_values.txt +++ b/01_values.txt @@ -1,493 +1,298 @@ -:chap_num: 1 -:prev_link: 00_intro -:next_link: 02_program_structure -:docid: values - -= Values, Types, and Operators = - -[chapterquote="true"] -[quote, Master Yuan-Ma, The Book of Programming] -____ -Below the surface of the -machine, the program moves. Without effort, it expands and contracts. -In great harmony, electrons scatter and regroup. The forms on the -monitor are but ripples on the water. The essence stays invisibly -below. -____ - -(((Yuan-Ma)))(((Book of Programming)))(((binary -data)))(((data)))(((bit)))(((memory)))Inside the computer's world, -there is only data. You can read data, modify data, create new -data—but anything that isn't data simply does not exist. All this data -is stored as long sequences of bits and is thus fundamentally alike. - -(((CD)))(((signal)))Bits are any kind of two-valued things, usually -described as zeros and ones. Inside the computer, they take forms -such as a high or low electrical charge, a strong or weak signal, or a -shiny or dull spot on the surface of a CD. Any piece of discrete -information can be reduced to a sequence of zeros and ones and thus -represented in bits. - -(((binary number)))(((radix)))(((decimal number)))For example, think -about how you might show the number 13 in bits. It works the same way -you write decimal numbers, but instead of 10 different ((digit))s, you -have only 2, and the weight of each increases by a factor of 2 from -right to left. Here are the bits that make up the number 13, with the -weights of the digits shown below them: - ----- - 0 0 0 0 1 1 0 1 - 128 64 32 16 8 4 2 1 ----- - -So that's the binary number 00001101, or 8 + 4 + 1, which equals 13. - -== Values == - -(((memory)))(((volatile data storage)))(((hard drive)))Imagine a sea of -bits. An ocean of them. A typical modern computer has more than 30 -billion bits in its volatile data storage. Nonvolatile storage (the -hard disk or equivalent) tends to have yet a few orders of magnitude -more. - -image::img/bit-sea.png[alt="The Ocean of Bits"] - -To be able to work with such quantities of bits without getting lost, -you can separate them into chunks that represent pieces of -information. In a JavaScript environment, those chunks are called -_((value))s_. Though all values are made of bits, they play different -roles. Every value has a ((type)) that determines its role. There are -six basic types of values in JavaScript: numbers, strings, Booleans, -objects, functions, and undefined values. - -(((garbage collection)))To create a value, you must merely invoke its -name. This is convenient. You don't have to gather building material -for your values or pay for them. You just call for one, and _woosh_, -you have it. They are not created from thin air, of course. Every -value has to be stored somewhere, and if you want to use a gigantic -amount of them at the same time, you might run out of bits. -Fortunately, this is a problem only if you need them all -simultaneously. As soon as you no longer use a value, it will -dissipate, leaving behind its bits to be recycled as building material -for the next generation of values. - -This chapter introduces the atomic elements of JavaScript programs, -that is, the simple value types and the operators that can act on such -values. - -== Numbers == - -(((syntax)))(((number)))(((number,notation)))Values of the -_number_ type are, unsurprisingly, numeric values. In a JavaScript -program, they are written as follows: - -[source,javascript] ----- -13 ----- - -(((binary number)))Use that in a program, and it will cause the bit -pattern for the number 13 to come into existence inside the computer's -memory. - -(((number,representation)))(((bit)))JavaScript uses a fixed -number of bits, namely 64 of them, to store a single number value. -There are only so many patterns you can make with 64 bits, which means -that the amount of different numbers that can be represented is -limited. For _N_ decimal ((digit))s, the amount of numbers that can be -represented is 10^_N_^. Similarly, given 64 binary digits, you can -represent 2^64^ different numbers, which is about 18 quintillion (an -18 with 18 zeros after it). This is a lot. - -Computer memory used to be a lot smaller, and people tended to use -groups of 8 or 16 bits to represent their numbers. It was easy to -accidentally _((overflow))_ such small numbers—to end up with a number -that did not fit into the given amount of bits. Today, even personal -computers have plenty of memory, so you are free to use 64-bit chunks, -which means you need to worry about overflow only when dealing with -truly astronomical numbers. - -(((sign)))(((floating-point number)))(((fractional number)))(((sign bit)))Not -all whole numbers below 18 quintillion fit in a JavaScript number, -though. Those bits also store negative numbers, so one bit indicates -the sign of the number. A bigger issue is that nonwhole numbers must -also be represented. To do this, some of the bits are used to store -the position of the decimal point. The actual maximum whole number -that can be stored is more in the range of 9 quadrillion (15 zeros), -which is still pleasantly huge. - -(((number,notation)))Fractional numbers are written by using a -dot. - -[source,javascript] ----- -9.81 ----- +CHAPTER ==>> 1 + + +Values, Types and Operators +Kabhi aapne socha hai, computer mei kaise kuch bhi store hota hai? Computer mei har cheez data ke form mei hoti hai, aapki files, aapka code, sab kuch. Aur data kaise store hota hai? Data bits ke form mei store hota hai. + +Bit ki 2 values hoti hai - zero aur one. Computer ke andar bits electrical charge ki form mei store hota hai - high signal matlab one, aur low signal matlab zero. + +Aapne kabhi socha hai CD mei data kaise store hota hai? + + + +CD mei jab data daalte hai, toh usmei chote chote pits (yaani gaddhe) ban jaate hai, jisko computer padh kar dekhta hai ki CD mei jo bits hai woh zero hai ya one. + +Kisi bhi information ko hum zeros aur ones ke roop mei likh sakte hai. Aisa karke hum woh information bits mei represent kar sakte hai. + +Chaliye, dekhte hai ki number 13 ko bits mein kaise likhenge. Jaise hum Maths mein decimal numbers likhte hai, vaise hi hum isse bhi likhenge. Lekin yaha Maths ke 10 (0-9) digits lene ki jagah hum sirf 2 digits lenge - zero aur one. + +1331 ko decimal system mei hum kaise likhte hai? +Ise hum 10 ke powers ki sum ke form me likh sakte hain. + +1000 100 10 1 + 1 3 3 1 + +1331 = 1000x1 + 100x3 + 10x3 + 1x1 +1331 = 103x1 + 102x3 + 101x3 + 100x1 + +Yaha humne 1331 ko 10 ki powers ke form me likha hai. 103 ko 1 se multiply karke aur isi tarah 102 ko 3, 101 ko 3 aur 100 ko 1 se multiply karne ke baad sum karke hume 1331 milega. + +Issi tarah hum pehle, 2 ki powers likhenge. 21, phir 4 (22 ), phir 8 (23 ), phir 16(24 ) aur jitni zaroorat ho aage badhte jaenge. 13 ki baat karein to ise hum 2 ke powers ke sum ki form me neeche diye hue tareeke se likh sakte hain :- + +8 4 2 1 +23 22 21 20 + 1 1 0 1 + + +13 = 8 + 4 + 1 +13 = 8x1 + 4x1 + 2x0 + 1x1 +13 = 23x1 + 22x1 + 21x0 + 20x1 -(((exponent)))(((scientific notation)))(((number,notation)))For -very big or very small numbers, you can also use scientific notation -by adding an “e” (for “exponent”), followed by the exponent of the -number: +Ab aap dekhein ki 2 ki powers ke sath multiply kiye hue numbers kaunse hain. 13 ka example lein to 2 ki powers 1, 1, 0 aur 1 se multiply hui hain. To 13 ki binary representation 1101 hui. Aap yeh sab dobara padhein , kyuki yeh pehli baar mein thoda confusing ho sakta hai. z -[source,javascript] ----- +Issi tarah 97 ko bits mein kaise likhenge? . Sabse pehle hum ise 2 ki powers ke sum ke form me likhenge. . 2 ki highest power wo hogi jiski value 97 se kam hogi. Hume pata hai ki 27 = 128 aur 26 = 64. 64, 97 se chhota hai isliye 26, 2 ki highest power hogi. Ab ise aise samajhne ki koshish karein. + +26 25 24 23 22 21 20 +64 32 16 8 4 2 1 +1 1 0 0 0 0 1 + +97 = 64 + 32 + 1 +97 = 64x1 + 32x1 + 16x0 + 8x0 + 4x0 + 2x0 + 1x1 +97 = 26x1 + 25x1 + 24x0 + 23x0 + 22x0 + 21x0 + 20x1 + +Yaha humne dekha ki 2 ki powers ko 1,1,0,0,0 aur 1 se multiply kiya gya hai, isliye 97 ka bits me representation hua 110001. +Is section mein aapne kisi bhi digit ka binary representation find out karne ka tareeka seekha. Aise hi aap 173 ko bhi binary number ki form (binary representation) mein likh sakte hain. +Hint: 173 = 128 + 32 + 8 + 4 + 1 +Values +Aap aise sochein ki ek samundra jis mein sirf bits hi bits hai. Ek modern computer mei 30 million yaani 3 crore se bhi jyada bits hoti hai. Javascript mei 6 tarah ki ‘data types’ hoti hai (jo bits ke roop mei store hoti hai) +numbers +strings +booleans +Objects booleans +objects +functions +undefined values + +Hum in types ke baarein mei aage aur details mei padhenge. + + +Numbers +“Number Type” ki value number hi hoti hai. Jo ki javascript program mein aise likhi jaati hai +>>> 13 +Isse console par likhne se number 13 ka bit representation computer memory mein aa jaata hai. + +Number ko memory mei store karne ke liye Javascript 64 bits use kar sakta hai. 64 bits use karke aap 264 numbers yaani lag bhag 18,000,000,000,000,000,000 jitne bade numbers store kar sakte hain . +Lekin computer ki memory uska bahut chota part use karti thi aur hum apne number ko represent karne k liye 8 se 16 bits use karte the.tab bahut assani se small number ka overflow ho jata tha aur wo hamare 8 se 16 bits mei fit nahi bethate the .lekin ab aise nahi hai, apna personal computer mei bhi bahut memory hai to hum pure 64 bits use kar sakte hai,iska matlab ye hua ki ab apko small number ke overflow ke chinta karne ki jarurt nahi hai. +Javascript number mei keval 18 quintullion se niche whole number hi nahi balki negative number bhi store hote hai ye sab bits ki wajah se hua.one bit kisi ek number ko represent karti hai.hum javascript mei nonwhole number ko bhi repersent kar sakte hai, iske liye kuch bits decimal point ki position ko bhi represent karte hai.fractional number ko dot ki help se likha jata hai. +9.81 +Bahut bade numbers ko short mei likne k liye ek scientific word use kiya jata hai iss word ko “e”(exponent) exponent number se represent karte hai. 2.998e8 ----- - -That is 2.998 × 10^8^ = 299,800,000. - -(((pi)))(((number,precision of)))(((floating-point -number)))Calculations with whole numbers (also called _((integer))s_) -smaller than the aforementioned 9 quadrillion are guaranteed to always -be precise. Unfortunately, calculations with fractional numbers are -generally not. Just as π (pi) cannot be precisely expressed by a -finite number of decimal digits, many numbers lose some precision when -only 64 bits are available to store them. This is a shame, but it -causes practical problems only in specific situations. The important -thing is to be aware of it and treat fractional digital numbers as -approximations, not as precise values. - -=== Arithmetic === - -(((syntax)))(((operator)))(((binary -operator)))(((arithmetic)))(((addition)))(((multiplication))) The main -thing to do with numbers is arithmetic. Arithmetic operations such as -addition or multiplication take two number values and produce a new -number from them. Here is what they look like in JavaScript: - -[source,javascript] ----- -100 + 4 * 11 ----- - -(((operator,application)))(((asterisk)))(((plus -character)))(((pass:[*] operator)))(((+ operator)))The `+` and `*` -symbols are called _operators_. The first stands for addition, and the -second stands for multiplication. Putting an operator between two -values will apply it to those values and produce a new value. - -(((grouping)))(((parentheses)))(((precedence)))Does the example mean -“add 4 and 100, and multiply the result by 11”, or is the -multiplication done before the adding? As you might have guessed, the -multiplication happens first. But as in mathematics, you can change -this by wrapping the addition in parentheses. - -[source,javascript] ----- -(100 + 4) * 11 ----- - -(((dash character)))(((slash -character)))(((division)))(((subtraction)))(((minus)))(((- -operator)))(((/ operator)))For subtraction, there is the `-` operator, -and division can be done with the `/` operator. - -When operators appear together without parentheses, the order in which -they are applied is determined by the _((precedence))_ of the -operators. The example shows that multiplication comes before -addition. The `/` operator has the same precedence as `*`. Likewise -for `+` and `-`. When multiple operators with the same precedence -appear next to each other, as in `1 - 2 + 1`, they are applied left -to right: `(1 - 2) + 1`. - -These rules of precedence are not something you should worry about. -When in doubt, just add parentheses. - -(((modulo operator)))(((division)))(((remainder operator)))(((% -operator)))There is one more arithmetic operator, which you might not -immediately recognize. The `%` symbol is used to represent the -_remainder_ operation. `X % Y` is the remainder of dividing `X` by -`Y`. For example, `314 % 100` produces `14`, and `144 % 12` gives `0`. -Remainder's precedence is the same as that of multiplication and -division. You'll often see this operator referred to as _modulo_, -though technically _remainder_ is more accurate. - -=== Special numbers === - -(((number,special values)))There are three special values in -JavaScript that are considered numbers but don't behave like normal -numbers. - -(((infinity)))The first two are `Infinity` and `-Infinity`, which -represent the positive and negative infinities. `Infinity - 1` is -still `Infinity`, and so on. Don't put too much trust in -infinity-based computation. It isn't mathematically solid, and it will -quickly lead to our next special number: `NaN`. - -(((NaN)))(((not a number)))(((division by zero)))`NaN` stands for “not -a number”, even though it is a value of the number type. You'll get -this result when you, for example, try to calculate `0 / 0` (zero -divided by zero), `Infinity - Infinity`, or any number of other -numeric operations that don't yield a precise, meaningful result. - -== Strings == - -(((syntax)))(((text)))(((character)))(((string,notation)))(((single-quote -character)))(((double-quote character)))(((quotation mark)))The next -basic data type is the _((string))_. Strings are used to represent -text. They are written by enclosing their content in quotes. - -[source,javascript] ----- -"Patch my boat with chewing gum" -'Monkeys wave goodbye' ----- - -Both single and double quotes can be used to mark strings as long as -the quotes at the start and the end of the string match. - -(((line break)))(((newline character)))Almost anything can be put -between quotes, and JavaScript will make a string value out of it. But -a few characters are more difficult. You can imagine how putting -quotes between quotes might be hard. _Newlines_ (the characters you -get when you press Enter) also can't be put between quotes. The string -has to stay on a single line. - -(((escaping,in strings)))(((backslash character)))To make it possible to include -such characters in a string, the following notation is used: whenever -a backslash (`\`) is found inside quoted text, it indicates that the -character after it has a special meaning. This is called _escaping_ -the character. A quote that is preceded by a backslash will not end -the string but be part of it. When an `n` character occurs after a -backslash, it is interpreted as a newline. Similarly, a `t` after a -backslash means a ((tab character)). Take the following string: - -[source,javascript] ----- -"This is the first line\nAnd this is the second" ----- - -The actual text contained is this: - ----- -This is the first line -And this is the second ----- - -There are, of course, situations where you want a backslash in a -string to be just a backslash, not a special code. If two backslashes -follow each other, they will collapse together, and only one will be -left in the resulting string value. This is how the string “++A newline -character is written like "\n".++” can be expressed: - -[source,javascript] ----- -"A newline character is written like \"\\n\"." ----- - -(((+ operator)))(((concatenation)))Strings cannot be divided, -multiplied, or subtracted, but the `+` operator _can_ be used on them. -It does not add, but it __concatenates__—it glues two strings together. -The following line will produce the string `"concatenate"`: - -[source,javascript] ----- -"con" + "cat" + "e" + "nate" ----- - -There are more ways of manipulating strings, which we will discuss -when we get to methods in link:04_data.html#methods[Chapter 4]. - -== Unary operators == - -(((operator)))(((typeof operator)))(((type)))Not all operators are -symbols. Some are written as words. One example is the `typeof` -operator, which produces a string value naming the type of the value -you give it. - -[source,javascript] ----- +Ko hum kholkar aise likhenge 2.998 X108 = 299800000000 +Whole number se calculation choti hoti ,according to jo humne pehle 9 quadrillion ke bare mei btaya tha.aisa fractional number ki calculation mei nahi hota.jaise Kabhi bhi π (pi) decimal mei koi finite number nahi deta,iska matalab iski koi bhi exect value hai hi nahi, thik issi tarah jab store karne ke liye 64 bits use hoti hai tab bahut se number apni actual value kho bathate hai lekin aisa keval kuch specifice situation mei hi hota hai .yah important cheeze ye hai ki fractional digit number ko hum ko approximation value se represent karte hai ,bajaye koi exact value diye. +Arithmetic +Numbers mein arithmetic sabse important hai. Arithmetic operations jaise addition, multiplication, division , etc. 2 ya 2 se jyada values lete hai.’ + Arithmetic operations solve hone ke baad ek nayi value milti hai + +Jaise ki 4+5=9. 4+5 solve karne se, 9 value milti hai. +Ek aur example: 100 + 4 * 11. Isse khud solve karein. . + +‘+’ , ‘*’, aur ‘/’ - inn symbols ko operators kaha jata hai. ‘+’ symbol addition ke liye, ‘*’ multiplication ke liye, aur ‘/’ symbol divide karne ke use hota hai. . Operator ko apply karne ke liye operator ko do value ke beech rakhte hai aur us operation ke result se humein ek nayi value milti hai. + +Upar jo expression khud solve karne ko diya hai , kya uska matlab “100 me 4 add kar ke 11 se multiply karna hai , ya fir phele “4 ko 11 se multiply kar ke phir 100 add karna hai ” ? Apne agar socha ki pehle multiplication hogi to aap sahi hain lekin aap is expression ko bracket laga ke change bhi kar sakte hain jisse phele addition hona chahiye ya multiplication, change ho jaega. + +Ab neeche diye expression ko dekhein aur sochein ki ise kaise solve karenge! + +Expression-1: (100 + 4) * 11 + +Jab bhi hum kisi expression ko solve karte hai to humei “BODMAS” rule ki jarurat padti hai. Toh aaiye hum pehle BODMAS ko samjhte hain. BODMAS ko break karein to hume milta hai: + +B = Brackets +O = Order(i.e. Powers,Square Roots, etc.) +D = Division +M = Multiplication +A = Addition +S = Subtraction + +Ek saath jab kai operations hote hai toh hum “BODMAS” ka use karke solve karte hai Sabse pehle kisi bhi expression mei brackets ko solve karte hai. Phir agar usmei koi powers ya square roots jaise expression hai to unko solve karte hai. Phir hum division ko solve karte hai. Uske baad multiply ko solve karte hai aur sabse aakhir mei hum addition aur subtraction ko solve karte hai. + +Isko aur ache se samjhne ke liye kuch example dekhte hai. + +7 + (6 × 25 + 3) +7 + (150 + 3) +7 + (153) +160 + +Ab iss rule ko use karte hue upar diye Expression-1 ko solve karein. + +Iske baad hum ek aur arithmetic operator ke baare me bat karenge jise hum remainder operator kehte hain. “%” symbol remainder operator ke liye use kiya jaata hai. + +30 / 3 = 10, remainder 0 + +35 / 3 = 11, remainder 2 + +Divide karne ke baad jo remainder bachta hai usko programming language mei modulus bolte hai or uske liye % ka symbol ka use kiya jaata hai. + +Special numbers +JavaScript mei kuch aisi value hoti hai jo number to hote hai, lekin woh normal number ki tarah behave nahi karte. + +Jaise pehli 2 value hai Infinity (∞) and - Infinity (-∞) jo positive aur negative infinities represent karte hai. “∞ - 1” bhi infinity hota hai, Isko aise samjho ki maan lo hamare paas infinite items hai. Un mei se ek do cheezein hatane par bhi, hamare paas infinite items hi bachenge. + +Hume infinity-based calculations par jayda wishwas nahi karna hai. Javascript mei yeh maths ka koi solid rule follow nahi karta. Ab hum apne dusre special number ki ore jayenge jo ki NaN ke baarein mei padhenge. + +NaN ka matlab “Not a Number” hota hai, vaise ye to ek number ka type hai lekin NAN ka matlab not a number hota hai. Agar humne 0/0, ∞ - ∞, ∞*3 kiya toh meaningful result nahi aata, isko javascript mei “not a number” bolte hai. + +Strings + +Agla basic data type string hai. Strings ko hum text ke liye use karte hai. String ko likhne ke liye hum quotes(“) use karte hai. String ki value quotes ke andar likhte hai. Isse Javascript samajh jata hai, ki jo quotes ke andar hai - woh string hai. + +Example +“Ye ek string hai” +“Ye string quotes mein hai” + +Strings ko likhne ke liye hum single quotes( ‘ ) ya double quotes ( “ ) dono ko use kar sakte hai. Par starting ka aur end ke quotes same hi hona chahiye. +``````````` +“ye ek string hai ” ‘ye ek string hai ‘ ye sahi tareeka hai + +Hum quotes ke andar kuch bhi value daal sakte hai. JavaScript usse strings ki taraha legi. Par strings me kuch value dalna thoda muskil ho sakta hai. Jaise aap soche ki string mei quotes kaise daalenge? + +Jaise +>>> “string ko double quotes (“) mei likh sakte ho” +Ismei problem samajh aayi? + +Javascript confuse ho jayega, aur samjhega “string ko double quotes (“ string hai. Uske aage jo likha hai, Javascript ko error lagega . + +Aise special (yaani vichitra) characters ke liye Javascript mei alag tareeka use kiya jaata hai. Jaise ki jab hum string ke andar backslash(\) use karte hai to anumaan laga sakte hai ki iske bad koi special character likha jayega. + +Jab \n likha jata hai toh iska matlab hota hai newline i.e. nayi line. Jab \t likha jaata hai, toh iska matlab hota hai tab. Dhyaan rakhe ki \ character ko backslash character bolte hai. Ab aap yeh sochein ki kisi ko agar backslash character likhna hai toh kaise likhega? Backslash character khud ek special character hai. Iske liye aapko \\ likhna hoga. + +"Yeh first line hai \n aur yeh second line hai” +Jo print karne par aisa dikhega: + +Yeh first line hai +aur yeh second line hai + +Toh agar aapko yeh print karana hai - “isme ek newline character likha hua hai "\n".” Dhyaan se dekhiye isme kaun kaun se special characters hai - “, \ aur “. Sab special characters se pehle backslash (yaani \) character daalna padega. + + +>>> “isme ek newline character likha hua hai \"\\n\".” +Output: isme ek newline character likha hua hai “\n”. + +Strings par hum divide ( / ), multiply ( * ) aur subtract ( - ) operators ka use nahi kar sakte. Par hum string me addition ( + ) operator ka use strings par kar sakte hai. + operator ka use karke hum do ya do se jada string ko ek sath concatenate (yaani chipka) sakte hai. Isko samjhne ke liye yeh example dekho - +>>> "con" + "cat" + "e" + "nate" +Output: "concatenate" + +Unary operators +Saare operator symbols nahi hote iska matlab ye hai ki kuch operator words ke bhi form mein hote hai. Jaise neeche diya hua example aisa hi ek operator hai + console.log(typeof 4.5) // → number console.log(typeof "x") // → string ----- - -[[console.log]] -(((console.log)))(((output)))(((JavaScript console)))We will use -`console.log` in example code to indicate that we want to see the -result of evaluating something. When you run such code, the value -produced should be shown on the screen, though how it appears will -depend on the JavaScript environment you use to run it. +Jaise aapne dekha ye example ek number type ka input le kar ek string type ki value produce kar rha hai par sochiye isne string type ki value kyu li. +Ye ek operator ki vajah se hua jiska naam “typeof” hai jo ki yha ek word ko operator ki tarah use kar rha hai. Isse wo uss value ka type yaani 4.5 ka type print kar dega . -(((negation)))(((- operator)))(((binary operator)))(((unary -operator)))The other operators we saw all operated on two values, but -`typeof` takes only one. Operators that use two values are called -_binary_ operators, while those that take one are called _unary_ -operators. The minus operator can be used both as a binary operator -and as a unary operator. +Hum apne example code ka result dekhne ke liye console.log ka use karenge. Jab aap yeh code run karoge to value screen par show honi chahiye, lekin jo value screen par dikhegi wo javscript ke environment par depend karegi ki javascript uss value ko kese dikhata hai. +Humne yaha dekha ki saare operaters do values pe operate hote hai (e.g. 3+4), lekin keval typeof ek aisa operater hai jo ek value pe operate hota hai. Jo operater 2 value pe operate hote hai wo binary operators kahlate hai, jabaki 1 value wale operate ko unary operators kehte hai . Dhayaan dein ki minus oprater ko hum unary and binary operater dono par use kar sakte hai Jaise yeh example dekhiye , -[source,javascript] ----- console.log(- (10 - 2)) // → -8 ----- +Boolean values +Kabhi kabhi hume aisa answer chahiye hota hai jiski do hi possibilities ho jaise “yes” aur “no” yaa “on” aur “off”. Iske liye javascript mei boolean type hota hai jo keval do possible results deta hai, true aur false (jinhe simply true aur false hi likhte hai). +Comparisons +Neeche diye examples mein Boolean values produce karne ke tareeke diya hua ha: -== Boolean values == - -(((Boolean)))(((operator)))(((true)))(((false)))(((bit)))Often, -you will need a value that simply distinguishes between two -possibilities, like “yes” and “no” or “on” and “off”. For this, -JavaScript has a _Boolean_ type, which has just two values: true and -false (which are written simply as those words). - -=== Comparisons === - -(((comparison)))Here is one way to produce Boolean values: - -[source,javascript] ----- console.log(3 > 2) // → true console.log(3 < 2) // → false ----- -(((comparison,of numbers)))(((> operator)))(((< operator)))(((greater -than)))(((less than)))The `>` and `<` signs are the traditional -symbols for “is greater than” and “is less than”, respectively. They -are binary operators. Applying them results in a Boolean value that -indicates whether they hold true in this case. -Strings can be compared in the same way. -[source,javascript] ----- +< symbol - “se chhota hai” ki jagah aur > symbol - “se bada hai” ki jagah hum bachpan se use karte aa rahe hain. Doosre Shabdon me “Chhota hai” ka symbol < aur “Bada hai” ka symbol hai > hota hai. .Yeh ek binary operator hai yani ise apply karne ke liye hume do values chaiye. Inn symbols ko use karne par result ek boolean value aati hai jisse yeh decide hota hai ki condition true hai ya false. +Same issi tarah se hum strings ki values bhi compare kar sakte hai. For example: + console.log("Aardvark" < "Zoroaster") // → true ----- - -(((comparison,of strings)))The way strings are ordered is more or less -alphabetic: uppercase letters are always “less” than lowercase ones, -so `"Z" < "a"` is true, and non-alphabetic characters (!, -, and so on) -are also included in the ordering. The actual comparison is based on -the _((Unicode))_ standard. This standard assigns a number to -virtually every character you would ever need, including characters -from Greek, Arabic, Japanese, Tamil, and so on. Having such numbers is -useful for storing strings inside a computer because it makes it -possible to represent them as a sequence of numbers. When comparing -strings, JavaScript goes over them from left to right, comparing the -numeric codes of the characters one by one. - -(((equality)))(((>= operator)))(((pass:[<=] operator)))(((== -operator)))(((!= operator)))Other similar operators are `>=` (greater -than or equal to), `<=` (less than or equal to), `==` (equal to), and -`!=` (not equal to). - -[source,javascript] ----- + +console.log("Rahul" < “rahul") +// → true + + +String me chhota ya bada compare karne ka alag tarika hota hai , aur choti abc hamesa badi ABC se badi hoti hai. + +Par actual comparison ke hum unicode standard ko use karenge, yeh standard har ek character ko ek number value deta hai jise use karke hum strings ko compare kar sakte hain. Aur character greek, arabic, japanese, tamil jaisi languages se liye jata hai( jaise maths mei hum “pie” padte hai jiski value “ 22/7” hoti hai). +Computer mei hume kuch string ki value store karne ki zarurat padati hai to hum aise numbers ka use kar sakte hai jisse hum asani se strings ko number ke sequence mein represent kar sakte hain. . +Jab hum do strings ko compare karte hai to javascript har character ko left to right padti hai aur uske numeric code ko one by one compare karti hai. + + + +Aur dusre operator bhi hain jaise >=(bada ya equal hai), <=(chota ya equal hai),==(equal hai) and !=(equal nahi hai ). Neeche diya hua example dekhiye + + console.log("Itchy" != "Scratchy") // → true ----- -(((comparison,of NaN)))(((NaN)))There is only one value in JavaScript -that is not equal to itself, and that is `NaN`, which stands for “not -a number”. +Jaisa ki obvious hai ki “Itchy” “Scratchy” ke equal nahi hai, Inpar equal nahi hai (!=) operator use karne se result true yaani sahi aata hai. + +Puri javascript mei ek value hai jo apne aap se equal nahi hoti woh hai NaN, jiska matlab hai “ Not for Number”. For example: + -[source,javascript] ----- console.log(NaN == NaN) // → false ----- -`NaN` is supposed to denote the result of a nonsensical computation, -and as such, it isn't equal to the result of any _other_ nonsensical -computations. +Basically NaN meaningless computation ko denote karta hai,aur yeh kisi dusri meaningless computation ke equal nahi hota . -=== Logical operators === -(((reasoning)))(((logical operators)))There are also some operations -that can be applied to Boolean values themselves. JavaScript supports -three logical operators: _and_, _or_, and _not_. These can be used to -“reason” about Booleans. -(((&& operator)))(((logical and)))The `&&` operator represents logical -_and_. It is a binary operator, and its result is true only if both -the values given to it are true. +Logical operators + +Yahan hum kuch aise operators use karenge jo boolean value par hi apply kiye ja sakte hai aur boolean result hi dete hai, iske liye javascript mein humein teen logical operators diye hue hai jaise - and, or aur not. +“and” operator ko represent karne k liye hum “&&” symbol use karte hai. Ye ek binary operator hai aur iska result true tabhi aata hai jab di hui dono condition true ho. Iska example neeche diye hue code me diya gya + -[source,javascript] ----- console.log(true && false) // → false console.log(true && true) // → true ----- -(((|| operator)))(((logical or)))The `||` operator denotes logical -_or_. It produces true if either of the values given to it is true. +Upar example mein aap dekh sakte hain ki agar dono conditions true nahi hai to result false hoga. + +“Or” operator ko hum “||“ symbol se denote karte hain. Agar di hui dono conditions mei se koi bhi ek condition true hogi to result mei true hi ayega. - Yaani jab dono conditions false hogi tabhi result false ayega otherwise result true ayega. + -[source,javascript] ----- -console.log(false || true) -// → true console.log(false || false) // → false ----- - -(((negation)))(((! operator)))_Not_ is written as an exclamation mark -(`!`). It is a unary operator that flips the value given to it—`!true` -produces `false` and `!false` gives `true`. - -(((precedence)))When mixing these Boolean operators with arithmetic -and other operators, it is not always obvious when parentheses are -needed. In practice, you can usually get by with knowing that of the -operators we have seen so far, `||` has the lowest precedence, then -comes `&&`, then the comparison operators (`>`, `==`, and so on), and -then the rest. This order has been chosen such that, in typical -expressions like the following one, as few parentheses as possible are -necessary: - -[source,javascript] ----- +console.log(true && false) +// → true + +Upar example mein aap dekh sakte hain ki agar dono conditions me se ek bhi true to result true hoga otherwise agar dono conditions false hui to result false hoga. + + Teesra logical operator hai “Not” jisko hum exclamation mark(!) se denote karte hain.Yeh ek aisa unary operator hai jo current value ko ulta kar deta hai. For example “!true” ka value hoga “false” aur “!false” ka result hoga “true”. + + +Jab hum inn boolean operator ko kisi dusre operators ya arithmetic operator ke saath use karte hai, tab yeh jaruri nahi hota ki hum brackets use karein - hum kar bhi sakte hai aur nahi bhi. +Aamtaur par humne practice karte hue yeh dekha hai ki || operator ki sabse kam preference hoti hai aur fir && aur fir comparison operator (<, >, ya ==) ko preference milti hai aur issi tarah baki ke operators ki bhi defined preference hai. Inki preference order iss hisaab se bnayi gayi hai ki brackets ke usage ke bina bhi expression evaluate ho jaye. For example: . + + + 1 + 1 == 2 && 10 * 10 > 50 ----- -(((conditional execution)))(((ternary operator)))(((?: -operator)))(((conditional operator)))(((colon character)))(((question -mark)))The last logical operator I will discuss is not unary, not -binary, but _ternary_, operating on three values. It is written with a -question mark and a colon, like this: +Upar diye expression ko operators ki preference ke hisaab se evaluate kar sakte hain. + +Lastly hum wo logical operator discuss karenge jo na to unary operator hai na to binary hai lekin wo ternary operator hai, jo teen operating values par execute hota hai. Yeh ek question mark(?) aur colon(:) use karke likha jata hai. For example: + -[source,javascript] ----- console.log(true ? 1 : 2); // → 1 console.log(false ? 1 : 2); // → 2 ----- -This one is called the _conditional_ operator (or sometimes just -_ternary_ operator since it is the only such operator in the -language). The value on the left of the question mark “picks” which of -the other two values will come out. When it is true, the middle value -is chosen, and when it is false, the value on the right comes out. +Isse conditional operator kahate hai (aur kabhi kabhi isse ternary operator bhi kehte hai). Question mark ke left wali value hi decide karti hai ki dusri dono value mein se kon si value result hogi. “?” mark ke left mein value agar true hui to “:” ke left wala final result hoga aur agar left mein value false hui to “:” ke right wala final result hoga. . + +Undefined values +Yaha hum aisi do special values ke bare mein padhenge jo meaningful value ke na hone ko darshaate hai, wo dono special values hain “null” aur “undefined”. Yeh aisi values hain jo apne paas kuch information store nahi karte. -== Undefined values == +Aapne Javascript language mein bhut sare operations dekhe honge ya dekhenge jo koi meaningful value produce nahi karte. Ye undefined value produce karte kyunki inhe kuch na value to return karni hi hai. . -(((undefined)))(((null)))There are two special values, written `null` -and `undefined`, that are used to denote the absence of a meaningful -value. They are themselves values, but they carry no -information. +Javascript design ke ander null and undefined values ka alag alag matlab hona Javascript ke design ka problem hai aur zyadatar in dono me koi fark nahi hota lekin kuch cases jaha hume inn dono values ke bare mein dekhna pade tab in dono koi ek doosre ki jagah use kar sakte hain. -Many operations in the language that don't produce a meaningful value -(you'll see some later) yield `undefined` simply because they have to -yield _some_ value. -The difference in meaning between `undefined` and `null` is an accident -of JavaScript's design, and it doesn't matter most of the time. In the cases -where you actually have to concern yourself with these values, I -recommend treating them as interchangeable (more on that in a moment). +Automatic type conversion -== Automatic type conversion == -(((NaN)))(((type coercion)))In the introduction, I mentioned that -JavaScript goes out of its way to accept almost any program you give -it, even programs that do odd things. This is nicely demonstrated by -the following expressions: +Introduction mein humne discuss kiya tha ki JavaScript zyada se programs ko run kar deta hai chahe usse ajeeb cheezein hi kyu na ho rahi ho! Chaliye kuch examples se ise samajhte hai. -[source,javascript] ----- console.log(8 * null) // → 0 console.log("5" - 1) @@ -498,125 +303,74 @@ console.log("five" * 2) // → NaN console.log(false == 0) // → true ----- - -(((+ operator)))(((arithmetic)))(((pass:[*] operator)))(((- -operator)))When an operator is applied to the “wrong” type of value, -JavaScript will quietly convert that value to the type it wants, using -a set of rules that often aren't what you want or expect. This is -called _((type coercion))_. So the `null` in the first expression becomes -`0`, and the `"5"` in the second expression becomes `5` (from string -to number). Yet in the third expression, `+` tries string -concatenation before numeric addition, so the `1` is converted to -`"1"` (from number to string). - -(((type coercion)))(((number,conversion to)))When something that -doesn't map to a number in an obvious way (such as `"five"` or -`undefined`) is converted to a number, the value `NaN` is produced. -Further arithmetic operations on `NaN` keep producing `NaN`, so if you -find yourself getting one of those in an unexpected place, look for -accidental type conversions. - -(((null)))(((undefined)))(((comparison,of undefined values)))(((== -operator)))When comparing values of the same type using `==`, the -outcome is easy to predict: you should get true when both values are -the same, except in the case of `NaN`. But when the types differ, -JavaScript uses a complicated and confusing set of rules to determine -what to do. In most cases, it just tries to convert one of the values -to the other value's type. However, when `null` or `undefined` occurs -on either side of the operator, it produces true only if both sides -are one of `null` or `undefined`. - -[source,javascript] ----- + + + + +Jaisa ki humne ab tak padha hai ki different operators different type ki values par apply hote hai par jab JavaScript me operators ko galat type ki values par apply kiya jata hai tab Javascript use apne hisaab se (Javascript ke internal rules use karke) , kisi type me convert kar deta hai aur phir unn values par operators ko apply karta hai. Is type ko transform karne ke process ko coercion kehte hain. Isse kayi aise results mil sakte hai jinke baare me aapne kabhi socha na ho. Jaise ki upar pehle example me null ko 0 me ‘coerce’ (convert) kar ke uspe multiply operator use hua hai jisse output 0 aata hai. Issi tarah doosre example me “5” jo ki ek string hai wo ek number me coerce ho gaya, jabki third example mein numerical 1, string type me convert hokar “1” ban gya hai jispe + operation lagne ke baad string concatenation ho gaya. + +Use ese tarike se chalta hai jaisa shayad apne wo socha na ho. Isko ko coercion bolte hai. Jesa ki apne phele exaple me dekha null ko 0 ki tarha use kiya hua hai. Or second example me “5” yani ek string value ko ek string ki tarha use kiya hua hai. Or third example me “5” yani ek string value ko 1 yani ek integer value ko ek sath jod diya hai to iss example me 1 ko yani integer value ko string ki tarha use kiya hia + + + +Jab koi cheej sahi tareeke se number me represent nahi hoti (for example: “five” ya undefined) aur use hum number me convert karne ki koshish karte hain tab wo NaN value produce karta hai. Agar apko aisa kuch result milta hai, tab apni type conversions ko dhyaan se dekhein ki kahin kuch gadbad to nahi hai. + + + + + +Ek jaisi data types ki values ko == ka use kar ke compare karna aur answer ka andaaza lagana easy hota hai. Yaani jab == operator ke dono sides ki values baraabar hongi to result true hoga. Par NaN par == operator lagaane par aisa nahi hoga. Agar operator ke dono sides ki values ka data type alag hota hai to JavaScript confuse ho jata hai ki kya jaaye. . Jadatar cases me JavaScript ek tarha (ek type) ki value ko dusri tarha ki value mai change karne ki kosish karta hai aur phir uspe operator apply hota hai. Par agar null aur undefined ka case dekhein to == operator true output tabhi dega jab dono side same ya in dono me se koi ek value ho. For example: + console.log(null == undefined); // → true console.log(null == 0); // → false ----- - -That last piece of behavior is often useful. When you want to test -whether a value has a real value instead of `null` or `undefined`, you -can simply compare it to `null` with the `==` (or `!=`) operator. - -(((type coercion)))(((Boolean,conversion to)))(((=== operator)))(((!== -operator)))(((comparison)))But what if you want to test whether -something refers to the precise value `false`? The rules for -converting strings and numbers to Boolean values state that `0`, -`NaN`, and the empty string (`""`) count as `false`, while all the -other values count as `true`. Because of this, expressions like `0 == -false` and `"" == false` are also true. For cases like this, where you -do _not_ want any automatic type conversions to happen, there are two -extra operators: `===` and `!==`. The first tests whether a value is -precisely equal to the other, and the second tests whether it is not -precisely equal. So `"" === false` is false as expected. - -I recommend using the three-character comparison operators defensively to -prevent unexpected type conversions from tripping you up. But when you're -certain the types on both sides will be the same, there is no problem with -using the shorter operators. - -=== Short-circuiting of logical operators === - -(((type coercion)))(((Boolean,conversion to)))(((operator)))The -logical operators `&&` and `||` handle values of different types in a -peculiar way. They will convert the value on their left side to -Boolean type in order to decide what to do, but depending on the -operator and the result of that conversion, they return either the -_original_ left-hand value or the right-hand value. - -(((|| operator)))The `||` operator, for example, will return the value -to its left when that can be converted to true and will return the -value on its right otherwise. This conversion works as you'd expect -for Boolean values and should do something analogous for values of -other types. - -[source,javascript] ----- + + + +Jo upar diya hua behavior hai wo jadatar useful hota hai. Jab aap test karna chahte hai ki jo value hai wo real hai ya nhi, to iske liye aap usse null operator ke sath compare kar sakte hai == (or !=) . + + +Par jab aap check karna chahte ho ki koi value exact hai ya nhi?. Numbers or string ko Boolean value me change karne ke rule me 0, NaN, aur khali string(“”) ka false count karta hai, jabki others value ko true count karta hai. Iske waje se, ese expressions me 0 == false aur "" == false true yeh true honge. Ese cases me, agar aap chahte hai ese automatic type conversions na ho, iske liye two opertors hai: === and !==. Jo pehla hai wo check karta hai ki value puri tarha se baki ki tarha hai. Aur jo dusra hai wo check karta hai ki value baki ki tarha nhi hai + + + +Islye aap tin character comparison use krna taki aap unexpected type conversions hone se rok sake aur aap isse paresan na ho paresan na ho . par jab ap sure(confirm) ho ki dono side ki ka type same hai to, to shorter operators ko use karne me bhi koi problem nhi hai. + + + +Short-circuiting of logical operators +Logical operators && and || ka alag data type ki values ko handle karne ke tareeke kaafi alag hain . Ye apne left side ki value ko khud se value ke hisaab se set kar dete hai (Boolean data type me convert karte hain jisse left hand side ya right hand side ki hi values aaye), lekin ye operator aur uske result pe depend karta hai ki kya result ayega ki original left hand value ayegi ya right hand value. + + +Jaise neeche diya gya example dekhein- jab || operator apne left side ki value ko true mei convert karega tab wo left value return(output) karega aur otherwise apne right ki value return krega.aisa aap boolean values se expect karte hai ye conversion waise hi kaam karta hai, aur kuch dusre value ke according similar value me coerce karne ki koshish karta hai. + + + console.log(null || "user") // → user console.log("Karl" || "user") // → Karl ----- - -(((default value)))This functionality allows the `||` operator to be -used as a way to fall back on a default value. If you give it an -expression that might produce an empty value on the left, the value on -the right will be used as a replacement in that case. - -(((&& operator)))The `&&` operator works similarly, but the other way -around. When the value to its left is something that converts to -false, it returns that value, and otherwise it returns the value on -its right. - -(((short-circuit evaluation)))Another important property of these two -operators is that the expression to their right is evaluated only when -necessary. In the case of `true || X`, no matter what `X` is—even if -it's an expression that does something __terrible__—the result will be -true, and `X` is never evaluated. The same goes for `false && X`, -which is false and will ignore `X`. This is called _short-circuit -evaluation_. - -(((ternary operator)))(((?: operator)))(((conditional operator)))The -conditional operator works in a similar way. The first expression is -always evaluated, but the second or third value, the one that is not -picked, is not. - -== Summary == - -We looked at four types of JavaScript values in this chapter: numbers, -strings, Booleans, and undefined values. - -Such values are created by typing in their name (`true`, `null`) or -value (`13`, `"abc"`). You can combine and transform values with -operators. We saw binary operators for arithmetic (`+`, `-`, `*`, `/`, -and `%`), string concatenation (`+`), comparison (`==`, `!=`, `===`, -`!==`, `<`, `>`, `<=`, `>=`), and logic (`&&`, `||`), as well as -several unary operators (`-` to negate a number, `!` to negate -logically, and `typeof` to find a value's type) and a ternary -operator (`?:`) to pick one of two values based on a third value. - -This gives you enough information to use JavaScript as a pocket -calculator, but not much more. The -link:02_program_structure.html#program_structure[next chapter] will -start tying these expressions together into basic programs. + +|| operator ko hum as a backup use kar sakte hai jisse ek default value to humein milegi hi. For example upar doosre line ke code me null || “user” expression se operator ke left mein empty value produce hogi, aur right side ki value uss value ko replace kregi matlab right value ke hissab se wo left side ki value set karega. + + +Jaise humne yaha || operator ka use karna seekha waise hi hum && operator ka bhi use karna seekhenge , fark sirf itna hai ki && operator ka use || operator se bilkul ulta hai. Pehle humne padha hai ki || operator apne dono side ki kisi bhi value ke true hone par output true deta hai jabki && operator apne dono side ki value agar true hai tabhi output true deta hai. Kuch cases aise bhi hote hai jab operator ke left side ki value agar coerce karke false banti hai to ye use return karta hai otherwise wo operator ke right side wali value return karta hai. + + + Dono operators ki ek important property hai ki right side ka expression tab hi coerce hokar change hota hai jab uski jarurat ho. Jaise ye case dekhein “true || X” iss expression mein X ki value kuch bhi ho issse koi fark nahi padta chaahe usse koi galat cheez hi ho rahi ho answer hamesha true hi hoga. X kabhi bhi calculate nahi hoga. Jaise iss example mein || operator ko apne left side me true dikhne par wo wahi ruk gay aur isse output produce hua true. . + +Issi tarike se && operator ka bhi us +e kiya jata hai aur ismei bhi && operator jaise hi apne left side par false value dekhta hai ye hamesha X ki value ko ignore kar deta hai. Dhayan rakhein ki || operator apne left side par false ki bajaaye true dekhta hai. Iss poore process ko short_circuit evaluation kahte hai. + + + +Thik issi tarah conditional operator bhi use kiye jate hai. First value hamesha pehle evaluate hoti hai aur second or third values ko wo tabhi consider karta hai jab unki zarurat ho. + + + + +Summary +Humne iss chapter me 4 tarah ki values ke baare me padha - numbers, strings, Booleans, aur undefined values. + +Inhe hum inke type ka naam likhkar (e.g. true ya null ) ya inki value likhkar (e.g. 13 ya “abc) define kar sakte hain. . Operators ka use kar ke values ko combine ya transform bhi kar sakte hai. Humne kuch aur binary operators ko bhi dekha. For example, Arithmetic operators (+, -, *, /, and %), String concatenation operator ( + ), string ko ek sath chipakne ke liye, or baaki doosri comparisons ke liye (==, !=, ===,!==, <, >, <=, >=), and logic test karne ke liye (&& , ||) ka usage jaana. diff --git a/02_program_structure.txt b/02_program_structure.txt index dc6d6eea8..3dfbb8034 100644 --- a/02_program_structure.txt +++ b/02_program_structure.txt @@ -1,432 +1,172 @@ -:chap_num: 2 -:prev_link: 01_values -:next_link: 03_functions - -= Program Structure = - -[chapterquote="true"] -[quote, _why, Why's (Poignant) Guide to Ruby] -____ -And my heart glows bright red under my -filmy, translucent skin and they have to administer 10cc of JavaScript -to get me to come back. (I respond well to toxins in the blood.) Man, -that stuff will kick the peaches right out your gills! -____ - -(((why)))(((Poignant Guide)))In this chapter, we will start to do -things that can actually be called _programming_. We will expand our -command of the JavaScript language beyond the nouns and sentence -fragments we've seen so far, to the point where we can -express some meaningful prose. - -== Expressions and statements == - -(((grammar)))(((syntax)))(((code,structure -of)))(((grammar)))(((JavaScript,syntax)))In -link:01_values.html#values[Chapter 1], we made some values and then -applied operators to them to get new values. Creating values like this -is an essential part of every JavaScript program, but it is only -a part. - -(((literal expression)))A fragment of code that produces a value is -called an _((expression))_. Every value that is written literally -(such as `22` or `"psychoanalysis"`) is an expression. An expression -between ((parentheses)) is also an expression, as is a ((binary -operator)) applied to two expressions or a unary operator applied to -one. - -(((nesting,of expressions)))(((human language)))This shows part of the -beauty of a language-based interface. Expressions can nest in a way -very similar to the way subsentences in human languages are nested—a -subsentence can contain its own subsentences, and so on. This allows -us to combine expressions to express arbitrarily complex computations. - -(((statement)))(((semicolon)))(((program)))If an expression -corresponds to a sentence fragment, a JavaScript _statement_ -corresponds to a full sentence in a human language. A program is -simply a list of statements. - -(((syntax)))The simplest kind of statement is an expression with a -semicolon after it. This is a program: - -[source,javascript] ----- -1; -!false; ----- - -It is a useless program, though. An ((expression)) can be content to -just produce a value, which can then be used by the enclosing -expression. A ((statement)) stands on its own and amounts to something -only if it affects the world. It could display something on the -screen—that counts as changing the world—or it could change the -internal state of the machine in a way that will affect the statements -that come after it. These changes are called _((side effect))s_. The -statements in the previous example just produce the values `1` and -`true` and then immediately throw them away. This leaves no impression -on the world at all. When executing the program, nothing observable -happens. - -(((programming style)))(((automatic semicolon -insertion)))(((semicolon)))In some cases, JavaScript allows you to -omit the semicolon at the end of a statement. In other cases, it has -to be there, or the next ((line)) will be treated as part of the same -statement. The rules for when it can be safely omitted are somewhat -complex and error-prone. In this book, every statement that needs a -semicolon will always be terminated by one. I recommend you do the -same in your own programs, at least until you've learned more about -subtleties involved in leaving out semicolons. - -== Variables == - -(((syntax)))(((variable,definition)))(((side effect)))(((memory)))How -does a program keep an internal ((state))? How does it remember -things? We have seen how to produce new values from old values, but -this does not change the old values, and the new value has to be -immediately used or it will dissipate again. To catch and hold values, -JavaScript provides a thing called a _variable_. - -[source,javascript] ----- -var caught = 5 * 5; ----- - -(((var keyword)))And that gives us our second kind of ((statement)). -The special word (_((keyword))_) `var` indicates that this sentence is -going to define a variable. It is followed by the name of the variable -and, if we want to immediately give it a value, by an `=` operator and -an expression. - -The previous statement creates a variable called `caught` and uses it -to grab hold of the number that is produced by multiplying 5 by 5. - -After a variable has been defined, its name can be used as an -((expression)). The value of such an expression is the value the -variable currently holds. Here's an example: - -[source,javascript] ----- +Chapter 2 +Program Structure + +Hi! Iss chapter mei hum vaastvik roop se programming ki shuruaat karenge. Pichle chapter mein hum ne javascript ki kuch simple commands ko samjha aur chalaya tha, ab iss chapter mei hum usse bade programs likhenge. + +Pehle chapter mein humne “values” ke bare mein padha aur unn par “operators” ka use kar ke basic mathematical operations ki. . Values create karna javascript me important hai. . +Kisi code ka ek chhota hisse jisse koi value produce ho usse hum expression kehte hai. Values jaise ki “42”, “swades movie”, etc. yeh sab expressions ke examples hai. + +Brackets ke beech mein likhe code ko bhi expression kehte hai. Agar hum do expressions ke beech me ek binary operator lagayein to isse bhi expression kahenge . Aur agar hum unary operator ek expression par lagaye usse bhi. Isse hume language based interface ki sundarta ka pata chalta hai. Javascript ko hum apni human language se compare kar sakte hai. +Jaise shabd, expression ke samaan hai. Aur sentence ek javascript statement ke. Issi tarah ek program bhot saari statements se banta hai. + +Halaki yeh program kaam ke nahi hai. Expression ek content bhi ho sakta hai jo sirf ek value ko produce kare, aur fir yeh value koi expression use kare. Ek satatement useful tabhi hoti agar wo kuch change kare. Yeh change display par kuch ho sakta hai ya kuch internal change ho sakta hai jo aane wali statement ko change karegi. Inn changes ko “side effects” kehte hai. Uper diye gaye examples me wo value “1” aur “true” ko produce karta hai, fir haath-on-haath/turant uska result de deta hai. Yeh kisi par koi impression nhi chodta. Kuch bhi aisa nhi hota jisse observe kiya ja sake jab hum program ko execute karte hai. Yeh ek useless program hai jo kuch change nhi kar rahe. + +Kabhi kabhar javascript hume statement ko semicolon ke bina end karne deta hai. Aur kabhi kabhi aisa nhi karne deta. Abhi yeh samjhna mushkil hai ki kab JS semicolon hatana allow karta hai aur kab nhi. Issiliyi abhi ke liye aap apne statements ko semi colon se end karna. Jab tak aap JS ki saari baarikiyan nhi samjhte. + +Aapne kabhi aise socha hai ki program internal state ko kaise yaad rakhta hai? aur kaise wo bhut saari cheezo ko yaad rakhta hai? Hume old values se new values produce karna aa gaya hai. Aur hum yeh bina old values change kiye bhi kar sakte hai. Inn new values ko store karne ke liye hum variables ka use karte hai. +Uper wala example humari agli type ki statement hai. “var” ek special word hai jo ye batata hai ki ek variable define hone wala hai. Iske baad hum variable ka naam likhte hai. Aur agr aap isse saath-saath value dena chahte hai to “=” operator ka use karte hai. + +var caught = 5 * 5; + +Jaise upar humne ek variable banaya jiska naam “caught” hai. Aur issme humne 5*5 ki value(25) ko store kara. +Jab hum variable defined kar dete hai , to uske baad hum iss variable ke naam ko ek expression ki tarah use kar sakte hai. Aur expression ki value, variable ki current value hoti hai. Jaise agar variable ki value 5 hai to expression ki value bhi 5 hogi. Example: var ten = 10; console.log(ten * ten); // → 100 ----- - -(((underscore character)))(((dollar -sign)))(((variable,naming)))Variable names can be any word that isn't -a reserved word (such as `var`). They may not include spaces. -Digits can also be part of variable names—`catch22` is a valid name, -for example—but the name must not start with a digit. A variable name -cannot include punctuation, except for the characters `$` and `_`. - -(((= operator)))(((assignment)))(((variable,assignment)))When a -variable points at a value, that does not mean it is tied to that -value forever. The `=` operator can be used at any time on existing -variables to disconnect them from their current value and have them -point to a new one. - -[source,javascript] ----- + +Hum variable ka koi bhi naam rakh sakte hai. Magar, iss baat ka dhyan rakhe ki variable ka naam koi bhi reserved word yaani ki koi bhi word jiska pehle se koi function hai( jaise “var”) nhi ho sakta. Variable ke naam mein spaces nhi aa sakte. Variable ke naam mein digits aa sakti hai jaise “catch22”, magar naam digits se start nhi ho sakta. Ismein “$” aur “_” ke ilawa aur koi special character hum nhi use kar sakte. + + +Jab hum variable ko ek value assign karte hai to iska yeh matlab nahi hai ki uss variable ki value hamesha wahi rahegi. Hum = operator ka use kar kar ek variable ko jab jarurat pade tab nayi value de sakte hai. Jasie :- + var mood = "light"; console.log(mood); // → light mood = "dark"; console.log(mood); // → dark ----- - -(((variable,model of)))(((tentacle (analogy))))You should -imagine variables as tentacles, rather than boxes. They do not -_contain_ values; they _grasp_ them—two variables can refer to the -same value. A program can access only the values that it still has a -hold on. When you need to remember something, you grow a tentacle to -hold on to it or you reattach one of your existing tentacles to it. - -image::img/octopus.jpg[alt="Variables as tentacles"] - -Let's look at an example. To remember the number of dollars that Luigi -still owes you, you create a variable. And then when he pays back $35, -you give this variable a new value. - -[source,javascript] ----- -var luigisDebt = 140; -luigisDebt = luigisDebt - 35; -console.log(luigisDebt); -// → 105 ----- - -(((undefined)))When you define a variable without giving it a value, -the tentacle has nothing to grasp, so it ends in thin air. If you ask -for the value of an empty variable, you'll get the value `undefined`. - -(((var keyword)))A single `var` statement may define multiple -variables. The definitions must be separated by commas. - -[source,javascript] ----- + +Variable ko aap boxes ke alawa jaal ki tarah samjh sakte hai. variable mei koi value nahi hoti balki yeh value ko samjhata hai -jaise 2 variable same value bhi represent kar sakte hai.program keval variable ki current value par execute hota hai ki uss variable ki abhi value kya hai.jab hume kuch cheeze ya diffrent value ki jrurat padegi to hum aapne variabe ya jaal ko bada krenge ya fir hum apne existing variable mei koi value attach karenge. +Aap variables ko tentacles yaani kissi animal ke haaton jaisa samajh sakte hai. Variables mein koi value nhi hoti. Yeh bass value ko pakad kar rakhte hai. App ek variable ki value tab tak use kar sakte hai jab tak usne value ko pakad kar rakha hoga. Jab bhi koi value store karni hoti hai, hum usse tentacle se pakad lete hai. Ya koi existing tentacle use kar lete hai. + + + + +Ek example lete hai. Yeh yaad rakhne ke liye ki aapko rahul se kitne paise lene hai, uske liye aap ek variable bana sakte hun. Jab rahul kuch paise de-dega tab aap uss variable ki value change kar sakte hai. + + +var rahulUdhar = 200; +rahulUdhar = rahulUdhar- 50; +console.log(rahulUdhar); +// → 150 +Agar hum variable define karte time usse koi value nhi dete, tab uske pass kuch pakadne ke liye nhi hota. Agar aap iss empty variable ki value print kroge to value undefined aayegi kyunki humne uss variable ko value nahi di thi. + +App neeche example mein dekh sakte hai ki kaise ek “var” statement se hum ek se zada variable define karte hai. Hum variables ke naam ko comma( , ) se separate kar kar likhte hai. aur isse hum commas se alag karte hai.jaise yeh example dekho-- var one = 1, two = 2; console.log(one + two); // → 3 ----- - -== Keywords and reserved words == - -(((syntax)))(((implements (reserved word))))(((interface (reserved -word))))(((let keyword)))(((package (reserved word))))(((private -(reserved word))))(((protected (reserved word))))(((public (reserved -word))))(((static (reserved word))))(((void operator)))(((yield -(reserved word))))(((reserved word)))(((variable,naming)))Words with -a special meaning, such as `var`, are _((keyword))s_, and they may not -be used as variable names. There are also a number of words that are -“reserved for use” in ((future)) versions of JavaScript. These are also -officially not allowed to be used as variable names, though some -JavaScript environments do allow them. The full list of keywords and -reserved words is rather long. - -[source,text/plain] ----- -break case catch class const continue debugger -default delete do else enum export extends false -finally for function if implements import in -instanceof interface let new null package private -protected public return static super switch this -throw true try typeof var void while with yield ----- - -Don't worry about memorizing these, but remember that this might be -the problem when a variable definition does not work as expected. - -== The environment == - -(((standard environment)))The collection of variables and their values -that exist at a given time is called the _((environment))_. When a -program starts up, this environment is not empty. It always contains -variables that are part of the language ((standard)), and most of the -time, it has variables that provide ways to interact with the -surrounding system. For example, in a ((browser)), there are variables -and functions to inspect and influence the currently loaded website -and to read ((mouse)) and ((keyboard)) input. - -== Functions == - -indexsee:[application (of functions),function application] -indexsee:[invoking (of functions),function application] -indexsee:[calling (of functions),function application] -(((output)))(((function)))(((function,application)))(((alert -function)))(((message box)))A lot of the values provided in the -default environment have the type _((function))_. A function is a -piece of program wrapped in a value. Such values can be _applied_ in -order to run the wrapped program. For example, in a ((browser)) -environment, the variable `alert` holds a function that shows a little -((dialog box)) with a message. It is used like this: - -[source,javascript] ----- + + +Har programming language me kuch aise words hote hai jinke sath pehle se ek special meaning juda hua hota hai, jaise ki "var". Aise words ko keywords bolte hai. Inn words ko hum variable ke naam ke liye use nhi kar sakte hai. Aise hi kuch aur words hote hai jinhe reserved words bolte hai. Inn words ko javascript future mein kisi special purpose ke liye use karegi. Issiliye iss tarah ke words ko aap VARIABLE ke naam ki tarah use nahi kar sakte.Jaise: + + +{ + "break case catch class const continue debugger + default delete do else enum export extends false + finally for function if implements import in + instanceof interface let new null package private + protected public return static super switch this + throw true try typeof var void while with yield" +} + +Inko yaad karna jaruri nhi hai. +Kissi bhi time ek program mein variables aur unki values ke collection ko environment kehte hai. Environment kabhi khali nhi hota. Environment mei humesha variable hote hai jo language ke standard system ka part hote hai. Aur isme aise variable bhi hote hai jinse aas-pass ki surroundig se baat ki jaye. Example, browser me kuch aise variable aur functions hote hai jinse hum load hui website se baat kar sakte hai. Aur keyboard aur mouse ki bhi input le sakte hai. + + +Bhot si default environment ki values function type ki hoti hai. Function +Environment mein bahut si values function type ki hoti hai. Aap functions ko toffees ki tarah soch sakte hai. Jaise toffee wrapper mein wrapped hoti hai. Ussi tarah functions ka code variables mein wrapped hota hai. Inn variables ka use kar kar hum unke dwara wrap kiye gaye code ko use kar sakte hai. Jaise, alert ek default environment variable hai jo ek function ka code wrapp karta hai. Yeh aise use hota hai, + +Yeh aise use hota hai. + alert("Good morning!"); ----- - -image::img/alert.png[alt="An alert dialog",width="8cm"] - -(((parameter)))(((function,application)))Executing a function is -called _invoking_, _calling_, or _applying_ it. You can call a -function by putting ((parentheses)) after an expression that produces a -function value. Usually you'll directly use the name of the variable -that holds the function. The values between the parentheses are given to -the program inside the function. In the example, the `alert` function -uses the string that we give it as the text to show in the dialog box. -Values given to functions are called _((argument))s_. The `alert` -function needs only one of them, but other functions might need a -different number or different types of arguments. - -== The console.log function == - -(((JavaScript console)))(((developer -tools)))(((Node.js)))(((console.log)))(((output)))The `alert` function -can be useful as an output device when experimenting, but clicking -away all those little windows will get on your nerves. In past -examples, we've used `console.log` to output values. Most JavaScript -systems (including all modern web ((browser))s and Node.js) provide a -`console.log` function that writes out its arguments to _some_ text -output device. In browsers, the output lands in the ((JavaScript -console)). This part of the browser interface is hidden by default, -but most browsers open it when you press F12 or, on Mac, when you -press Command-Option-I. If that does not work, search through the -menus for an item named “web console” or “developer tools”. - -ifdef::interactive_target[] - -When running the examples, or your own code, on the pages of this -book, `console.log` output will be shown after the example, instead of -in the browser's JavaScript console. - -endif::interactive_target[] - -[source,javascript] ----- + +Functions ko execute karne ko invoking, calling ya applying kehte hai. Hum ek function ko call karne k liye uss expression ke baad brackets lagate hai jo ki function ki value produce kar rha hai. Jyadater aap direct uss variable ka naam use karoge jisme function hai. Jo value brackets ke beech mein likhi jaati hai, wo value function ke andar program ko di jaati hai. Jaise ki, alert function ek string value leta hai aur usse dialog box mein show karta hai. Inn values ko hum arguments bolte hai. Alert function ko sirf ek argument ki jarurt hoti hai. Par dusre functions ek se jyada aur different type ke arguments bhi le sakte hai. + + +Alert function, apne program ke saath experiment karte hue kuch output karne ke liye use kiya ja sakta hai. Magar baar-baar dialog box par click karna irritating ho sakta hai. Issi Liye hum console.log ka use karte hai. Humne console.log ka use upar wale examples mein bhi kiya hai. Jyadatar systems jahan hum javascript ka code likhte hai, wo console.log ko support karte hai. Yeh function apne arguments ko kissi text output device (jaise, browser console) par likhta hai. Browser mein yeh output console par aati hai. Aap apne browser mein “f12” ya Mac mein Command-Option-I press kar kar console open kar sakte hai. Aur agar yeh nahi kaam karta to, “web console” ya “developer tools” ka option apne browser ki settings mein search kare. + + var x = 30; console.log("the value of x is", x); // → the value of x is 30 ----- - -(((object)))Though ((variable)) names cannot contain ((period -character))s, `console.log` clearly has one. This is because -`console.log` isn't a simple variable. It is actually an expression -that retrieves the `log` ((property)) from the value held by the -`console` variable. We will find out exactly what this means in -link:04_data.html#properties[Chapter 4]. - -[[return_values]] -== Return values == - -(((comparison,of numbers)))(((return value)))(((Math.max -function)))(((maximum)))Showing a dialog box or writing text to -the screen is a _((side effect))_. A lot of functions are useful -because of the side effects they produce. Functions may also produce -values, and in that case, they don't need to have a side effect to be -useful. For example, the function `Math.max` takes any number of -number values and gives back the greatest. - -[source,javascript] ----- + + +Haala ki variable k naam me special character nhi ho sakte, lekin “console.log” me hai. Aisa isliye hai kyuki console.log ek simple variable nhi hai. Yeh ek expression hai jo ki console variable se log property nikalta hai. Iske baare mein hum aur Chapter 4 mein padhenge. + +Window par dialog box show karna ya screen par text likhna, ek tarha ke side effects hai. Bahut sare functions aapne side effects ki wajah se useful hote hai. Functions values bhi produce kar sakte hai, iss case mai unko useful hone ke liye side effects ki jarurat nhi hai. For example, Math.max function ek se jyada numbers mein se sabse bada number deta hai. console.log(Math.max(2, 4)); // → 4 ----- -(((function,application)))(((minimum)))(((Math.min -function)))When a function produces a value, it is said to _return_ -that value. Anything that produces a value is an ((expression)) in -JavaScript, which means function calls can be used within larger -expressions. Here a call to `Math.min`, which is the opposite of -`Math.max`, is used as an input to the plus operator: -[source,javascript] ----- +Functions value ko produce kar kar, uss value ko return karte hai. Aur jo bhi cheez koi value produce karti hai usse javascript mein ek expression bolte hai. Iska matlab hum function calls ko bhi expressions mein use kar sakte hai. Jaise humne iss example mein Math.min aur plus operator ko saath mein use kiya hai. console.log(Math.min(2, 4) + 100); // → 102 ----- -The link:03_functions.html#functions[next chapter] explains how to -write your own functions. +Next chapter mein hum apne functions likhna seekhenge. -== prompt and confirm == -(((dialog box)))(((input)))(((browser)))(((confirm function)))Browser -environments contain other functions besides `alert` for popping up -windows. You can ask the user an OK/Cancel question using -`confirm`. This returns a Boolean: `true` if the user clicks OK and -`false` if the user clicks Cancel. +prompt and confirm + +Browser ke environment mei aur bhut sare function hote hai alert ke alawa jo dialog box display karte hai. Confirm ka use kar kar aap user se question pooch sakte hai. User inka jawab OK ya CANCEL par click kar kar deta hai. Agar user OK click karta hai to Boolean true return hota hai. Aur agar cancel to Boolean false. Jaise, -[source,javascript] ----- confirm("Shall we, then?"); ----- -image::img/confirm.png[alt="A confirm dialog",width="8cm"] -(((input)))(((prompt function)))(((text input)))The `prompt` function -can be used to ask an “open” question. The first argument is the -question, the second one is the text that the user starts with. A line -of text can be typed into the dialog window, and the function will -return this text as a string. +Dusra function hai “prompt”. Iska use karke hum user se ek question ka answer puch sakte hai. User ka answer prompt function ek string mein return karta hai. Yeh function 2 arguments leta hai. Pehli argument mein hum question likhte hai. Aur dusri mein hum wo text likhte hai jisse user likhna shuru karega. Jaise, -[source,javascript] ----- prompt("Tell me everything you know.", "..."); ----- - -image::img/prompt.png[alt="An prompt dialog",width="8cm"] -These two functions aren't used much in modern web programming, mostly -because you have no control over the way the resulting windows look, -but they are useful for toy programs and experiments. -== Control flow == -(((execution order)))(((program)))(((control flow)))When your program -contains more than one ((statement)), the statements are executed, -predictably, from top to bottom. As a basic example, this program has -two statements. The first one asks the user for a number, and the -second, which is executed afterward, shows the ((square)) of that -number. +Control flow -[source,javascript] ----- -var theNumber = Number(prompt("Pick a number", "")); -alert("Your number is the square root of " + - theNumber * theNumber); ----- +Jab aapke program mei ek se jayada statement hoti hai , tab statements upar se niche ki taraf execute hoti hai. Jaise, iss program mei 2 statements hai. Pehli statement user se ek number input leti hai. Aur dusri statement, jo bad mei execute hogi wo uss number ka square show legi. -(((number,conversion to)))(((type coercion)))(((Number -function)))(((String function)))(((Boolean -function)))(((Boolean,conversion to)))The function `Number` converts a -value to a number. We need that conversion because the result of -`prompt` is a string value, and we want a number. There are similar -functions called `String` and `Boolean` that convert values to those -types. +var theNumber =Number(prompt("Pick a number", "")); +alert("Your number is the square root of " + theNumber * theNumber); -Here is the rather trivial schematic representation of straight -control flow: -image::img/controlflow-straight.svg[alt="Trivial control flow",width="4cm"] +Upar diye gaye example mein humne user se input lene ke liye prompt function ka use kiya hai. Aur uss value ko output karne ke liye alert ka use kiya hai. +Humne “number” function ka use “string” value ko number mein convert karne ke liye kiya hai. Aisa isliye kiya hai kyunki prompt function humesha ek string value return karta hai aur square nikalne ke liye hume ek number ki jarurat hai. +Issi tarah “string” aur “boolean” naam ke functions hai jo values ko inn type mein convert karte hai. -== Conditional execution == -(((Boolean)))(((control flow)))Executing statements in straight-line -order isn't the only option we have. An alternative is _((conditional -execution))_, where we choose between two different routes based on a -Boolean value, like this: +Conditional execution -image::img/controlflow-if.svg[alt="Conditional control flow",width="4cm"] +Hum statements ko straight line ke ilawa aur ways mein bhi execute kar sakte hai. Conditional execution ek aisa tareeka hai. Iss mein boolean value “true” ya “false” se aage ka rasta pata chalta hai. Jaise, Agar condition hai : -(((syntax)))(((Number function)))(((if keyword)))Conditional execution -is written with the `if` keyword in JavaScript. In the simple case, we -just want some code to be executed if, and only if, a certain -condition holds. For example, in the previous program, we might want -to show the square of the input only if the input is actually a -number. +aapko bhook lagi hai ? +True, to khalo! +False, to mat kaho! -[source,javascript] ----- -var theNumber = Number(prompt("Pick a number", "")); -if (!isNaN(theNumber)) - alert("Your number is the square root of " + - theNumber * theNumber); ----- +Aise control flow ko hum digaram se aise represent kar sakte hai. -With this modification, if you enter “cheese”, no output will be shown. -The keyword `if` executes or skips a statement depending on the value -of a Boolean expression. The deciding expression is written after the -keyword, between ((parentheses)), followed by the statement to execute. +If ( condition ) // agar condition true value degi tab code chalega + { // aur false to nhi + //code +} +var theNumber =Number(prompt("Pick a number", "")); +alert("Your number is the square root of " + + theNumber * theNumber); +Jaise hum iss example mei tab hi input ka square compute karenge jab input ek number ho. -(((isNaN function)))The `isNaN` function is a standard JavaScript -function that returns `true` only if the argument it is given is -`NaN`. The `Number` function happens to return `NaN` when you give it -a string that doesn't represent a valid number. Thus, the condition -translates to “unless `theNumber` is not-a-number, do this”. +Ab agar hum koi string value input karenge jaise “twentyThree”. Tab if ke andar wali condition ka result false ayega. Aur if ke andar likha code nahi chalega. -(((else keyword)))You often won't just have code that executes when a -condition holds true, but also code that handles the other case. This -alternate path is represented by the second arrow in the -diagram. The `else` keyword can be used, together with `if`, to create -two separate, alternative execution paths. +isNaN function ek standard javascript function hai jo true value tab return karta hai jab given value NaN(not a number) yaani wo value number na ho . Aur false jab value number ho. +Aur agar hum !isNan likhte hai, to yeh true tab return karega jab value number hogi. +Aur, number function NaN tab return karta hai jab string value mein number na ho. Warna wo string ko number mein convert karta. -[source,javascript] ----- var theNumber = Number(prompt("Pick a number", "")); if (!isNaN(theNumber)) alert("Your number is the square root of " + theNumber * theNumber); else alert("Hey. Why didn't you give me a number?"); ----- -(((if keyword,chaining)))If we have more than two paths to choose -from, multiple `if`/`else` pairs can be “chained” together. Here's an -example: +Agar humare pass ek se jyada “conditions” hai, to hum multiple yaani ki ek se jyada if/else statements bhi use kar sakte hai. Jaise, + -[source,javascript] ----- var num = Number(prompt("Pick a number", "0")); if (num < 10) @@ -435,27 +175,19 @@ else if (num < 100) alert("Medium"); else alert("Large"); ----- +Iss program mei sabse pehle user se ek nuber input lenge prompt function ka use kar kar. Uske baad hum check karenge ki kya yeh number 10 se kam hai? iAgar hai to “small” show karo. Aur ye program yahi khatam ho jayega.Agar number 10 kam nahi hai, to program else statement pe jayega. Yahan else statement mei hi second if statement hai.Second condition mei (num<100) ye condition likhi hai. Iska matlab hai ki kya number 10 aur 100 ke bich mei hai? Agar hai to “medium” show kro. Agar inn dono conditions mei se koi bhi condition true nahi ho rahi to last wali else statement execute hogi. Aur wo large show karegi. + -The program will first check whether `num` is less than 10. If it is, -it chooses that branch, shows `"Small"`, and is done. If it isn't, it -takes the `else` branch, which itself contains a second `if`. If the -second condition (`< 100`) holds, that means the number is between 10 -and 100, and `"Medium"` is shown. If it doesn't, the second, and last, -`else` branch is chosen. -The flow chart for this program looks something like this: +Jaise aap ye flow chart ko dekh ke ache se samjh jaoge, ye uppper if/else if/else statement ko represent karti hai- -image::img/controlflow-nested-if.svg[alt="Nested if control flow",width="4cm"] -[[loops]] -== while and do loops == -(((even number)))Consider a program that prints all even numbers from -0 to 12. One way to write this is as follows: +while and do loops + +Agar aapko ek program likhna hai jo 0 se 12 tak sare even numbers print kare. Ek tarika to yeh hai ki hum her ek even number ko khud print kare. Jaise, : + -[source,javascript] ----- console.log(0); console.log(2); console.log(4); @@ -463,23 +195,13 @@ console.log(6); console.log(8); console.log(10); console.log(12); ----- -(((control flow)))That works, but the idea of writing a program is to -make something _less_ work, not more. If we needed all even numbers -less than 1,000, the previous would be unworkable. What we need is a -way to repeat some code. This form of control flow is called a -_((loop))_: +Yeh program kaam to sahi karega. Magar socho, agar aapko 0 se 10000 tak saare even numbers print karne hai? Hum ek-ek number ko khud console.log nhi karenge. Hume koi aisa tarika chahiye jisse yeh kaam hum baar-baar kar sake. Aur jyada lines ka program bhi na likhna pade. Aise control flow ko hum “loop” kehte hai. +Ye kaam to sahi kar rha hai lekin isse likhne liye hume bhut lamba code likhna pad rha hai(ismei ek cheeze bar bar repeat ho rhi hai) aur agar hume 0 se 12 ke bajay 0 se 10000 tak ke sare even number print karne ho to mujjhe bhut lamba program likhna padega to pehla wala tarika to use nahi karenge.to iske liye hume kuch code ko bar bar repeat karna padega ,iss type ke control flow ko hume loop kahte hai jaise ye diagram dekho: -image::img/controlflow-loop.svg[alt="Loop control flow",width="4cm"] +Loop, se hum control flow ko program mei kissi point par wapas le ja sakte hai. Aur, firse wahi code chala sakte hai. Jaise, agar aapne ek baar print kiya “hello world”. Hum loop ka use karke baar-baar “hello world” print kara sakte hai. +Javascript mein loop “teen” ways se use kar sakte hai. “While”, “do while” aur “for” loop. Pehle hum while loop ke baare mei padenge. Example, -(((syntax)))(((counter variable)))Looping control flow allows us to go -back to some point in the program where we were before and repeat it -with our current program state. If we combine this with a variable -that counts, we can do something like this: - -[source,javascript] ----- var number = 0; while (number <= 12) { console.log(number); @@ -488,44 +210,21 @@ while (number <= 12) { // → 0 // → 2 // … etcetera ----- - -(((while loop)))(((Boolean)))A ((statement)) starting with the -keyword `while` creates a loop. The word `while` is followed by an -((expression)) in ((parentheses)) and then a statement, much like `if`. -The loop executes that statement as long as the expression produces a -value that is `true` when converted to Boolean type. - -(((grouping)))((({} (block))))(((block)))In this loop, we want to both -print the current number and add two to our variable. Whenever we need -to execute multiple ((statement))s inside a loop, we wrap them in -((curly braces)) (`{` and `}`). Braces do for statements what -((parentheses)) do for expressions: they group them together, making -them count as a single statement. A sequence of statements wrapped in -braces is called a _block_. - -(((programming style)))Many JavaScript programmers wrap every single -loop or `if` body in braces. They do this both for the sake of -consistency and to avoid having to add or remove braces when changing -the number of statements in the body later. In this book, I will write -most single-statement bodies without braces, since I value brevity. -You are free to go with whichever style you prefer. - -(((comparison)))(((state)))The variable `number` demonstrates the way -a ((variable)) can track the progress of a program. Every time the -loop repeats, `number` is incremented by `2`. Then, at the beginning -of every repetition, it is compared with the number `12` to decide -whether the program has done all the work it intended to do. - -(((exponentiation)))As an example that actually does something useful, -we can now write a program that calculates and shows the value of -2^10^ (2 to the 10th power). We use two variables: one to keep -track of our result and one to count how often we have multiplied this -result by 2. The loop tests whether the second variable has reached 10 -yet and then updates both variables. - -[source,javascript] ----- + +Iss example mein humne pehle, number variable ki value zero kar di hai. Fir control flow “while” keyword par aayega aur samajh jayega ki loop start ho gaya hai. Agar while ki condition ka result true aata hai, to iske andar likha code execute hoga. Computer 0<= 12 condition ka result compute karega, jo ki true value dega. Aur while ke andar likha code chal jayega. Pehle number print karega. Firr uski value 2 se badegi, aur control flow dubara upar jaa kar condition ka result nikalega. Iss baar 2<=12 check hoga. Iska result bhi true ayega. Aur firr while ka code chalgea. Issi tarah jab tak number ki value 14 nhi ho jaati tab tak while ka code chalta rahega. + +While ke andar ek se jyada statements likhne ke liye hum braces yaani { } ka uske karte hai. Jaise humne upar wale example mein kiya hai. Braces mein likhe lines ko hum “block” kehte hai. Jaise, + +{ line1 … +line2… +line3 … +} +Line1 se line3 tak statements ko hum ek “block” bol sakte hai. +Generally, hum ek statement ko bhi braces mein likhte hai. Taaki program banate time confusion na ho. Aur agar hume baad mein while ya if mein agar ek se jyada line likhni pade to braces na add karne pade. + + +Jaise hum ek example lete hai ,hume ek program likhna hai jo 210 (2 ki power 10) ki value calculate kare.iske liye hume 2 variabl banayenge :jismei se ek hamare result ko represent kare aur dusara number of multiply count kare matlab kitni bar multiply ho rahi hai ye count kare kyuki hume keval 10 bar hi multiply karna hai.jaise hi second variable ki value 10 ho jayegi tab loop ruk jayega aur dono variable ki value update honi bhi band ho jayegi . + var result = 1; var counter = 0; while (counter < 10) { @@ -534,209 +233,138 @@ while (counter < 10) { } console.log(result); // → 1024 ----- +Iss example mein hum counter ki value 1 bhi rakh sakte the. Aur number<10 ki jagah number <= 10 check kar sakte the. Magar humne counter ki value 0 se start kari. Humne aisa kyun kiya? Iska answer aapko chapter 4 mein milega. -The counter could also start at `1` and check for `<= 10`, but, for -reasons that will become apparent in -link:04_data.html#array_indexing[Chapter 4], it is a good idea to get -used to counting from 0. +do { + var Naa = prompt("Aap kaun hai?"); +} while (!Naam); +console.log(Naam); + +Yeh loop tab tak chalta rahega jab tak user koi “non-empty string” yaani ki aise string jo khaali nhi ho input nhi karta. Aisa isliye kyunki pehle control flow “do” par aayega. Uske baad “prompt” function execute hoga aur user se input lega. Agar user kuch input nhi karta to condition “!Naam” true ho jayegi. Aur control flow wapas upar chala jayega. Magar, agar user kuch input kar deta hai, to yeh condition false ho jayegi. Aur hum loop se bahar aa jayenge. Firr, console.log function se user ka naam console par print ho jayega. + + + + +Indenting Code + +Aapne, shayad yeh notice kar liya hoga ki mein kuch statements ke shuruaat mein khaali jagah chod deta hun(spaces) aur kuch ke aage nhi. Aisa karna javascript mein jaruri nhi hai. Hum ek line mein bhi pura program likh sakte hai. Magar, aisa karne se program mein galtiyan aur program samjhne mein mushkil hogi. Isliye hum indentation ka use karte hai. Yaani ki hum “code blocks” ke shuruat mein spaces daalte hai. Taaki code debug karna aur padhna easy ho jaye. + + +Bade aur complex programs mei “nested blocks” yaani ek ke andar ek blocks ho sakte hai. Agar hum blocks ko indent nhi karte, to yeh samjhna ki koi block kahan se shuru hai aur kahan end ho raha hai bhot mushkil ho jata hai. Magar sahi indentation ka use kar kar yeh samjhna aur easy ho jata hai. +Iss book mein meine indentation ke liye 2 spaces ka use kiya hai. Kai programmers 4 spaces ya “tab” character ka bhi use karte hai. + + + +Apne shayad notice kiya hoga ki statements se phele kuch space diya hua hai. javaScript me space dalna jaruri nhi hota iske bina nhi apka code run ho jaega. Aap javaScript me ek hi line me bhi sara code likh sakte hai. Indention ka use code ko structure dene ke liye hota hai taki bad me aap isko aasani se padh aur samjh sako. Jab code bada aur thoda muskil hota hai to usme smjhna muskil ho sakta hai ki kaha par blocks open hai or kaha par end hai. Ache se identation se aap ko yeh chije smjhne me muskil nhi hogi. + + + +for loops + +Jyadatar loops while loop jaisa hi pattern use karte hai. Jaise while loop mein sabse pehle hum ek counter bante hai jo loop ki progress dekhta hai. Uske baad while keyword use karte . Fir isme counter ki value condition se compare hoti hai. Agar condition true hoti hai tab loop ki body chalti hai. Aur agar false, tab body nahi chalti.Loop ki body ke last mei counter variable update kiya jata hai.Yeh pattern itna common hai, isliye javascript hume isse likhne ke liye ek aur tareeka deti hai: For Loop. Jaise, -(((loop body)))(((do loop)))(((control flow)))The `do` loop is a -control structure similar to the `while` loop. It differs only on one -point: a `do` loop always executes its body at least once, and it -starts testing whether it should stop only after that first execution. -To reflect this, the test appears after the body of the loop: -[source,javascript] ----- -do { - var yourName = prompt("Who are you?"); -} while (!yourName); -console.log(yourName); ----- - -(((Boolean,conversion to)))(((! operator)))This program will -force you to enter a name. It will ask again and again until it gets -something that is not an empty string. Applying the `!` operator will -convert a value to Boolean type before negating it, and all strings -except `""` convert to `true`. This means the loop continues going round -until you provide a name that is not the empty string. - -== Indenting Code == - -(((block)))(((code structure)))(((whitespace)))(((programming -style)))You've probably noticed the spaces I put in front of some -statements. In JavaScript, these are not required—the computer will -accept the program just fine without them. In fact, even the ((line)) -breaks in programs are optional. You could write a program as a single -long line if you felt like it. The role of the ((indentation)) inside -blocks is to make the structure of the code stand out. In complex -code, where new blocks are opened inside other blocks, it can become -hard to see where one block ends and another begins. With proper -indentation, the visual shape of a program corresponds to the shape of -the blocks inside it. I like to use two spaces for every open block, -but tastes differ—some people use four spaces, and some people use -((tab character))s. - -== for loops == - -(((syntax)))(((while loop)))(((counter variable)))Many loops follow -the pattern seen in the previous `while` examples. First, a “counter” -variable is created to track the progress of the loop. Then comes a -`while` loop, whose test expression usually checks whether the counter -has reached some boundary yet. At the end of the loop body, the -counter is updated to track progress. - -(((for loop)))(((loop)))Because this pattern is so common, JavaScript and -similar languages provide a slightly shorter and more comprehensive -form, the `for` loop. - -[source,javascript] ----- for (var number = 0; number <= 12; number = number + 2) console.log(number); // → 0 // → 2 // … etcetera ----- -(((control flow)))(((state)))This program is exactly equivalent to the -link:02_program_structure.html#loops[earlier] even-number-printing -example. The only change is that all the ((statement))s that are -related to the “state” of the loop are now grouped together. +Yeh example bhi pichle even-number wale example ki tarah hai. Yaha bas ek diffrent hai ki jo bhi statements loop ke state ke related thi ab wo sari ek sath group me hai + -The ((parentheses)) after a `for` keyword must contain two -((semicolon))s. The part before the first semicolon _initializes_ the -loop, usually by defining a ((variable)). The second part is the -((expression)) that _checks_ whether the loop must continue. The final -part _updates_ the state of the loop after every iteration. In most -cases, this is shorter and clearer than a `while` construct. +For keywords me brackets ke bad me semicolons lagane jaruri hota hai. first semicolon ke aage wala part yeh decide karta hai ki loop kha se start ho raha hai jo generally hum usse variable se defined karte hai. +Aur second part ek expression hota hai jo yeh check karta hai ki loop kha tak chalna chahiye. Aur last part har iteration ke bad loop ki state change hoti hai matlab variable ki value change hoti rahti hai.jaydatar yeh tarika while loop wale tarike se chota aru clear hota hai. +Yha 210 hai ka code likha hai while loop ke bina : -(((exponentiation)))Here is the code that computes 2^10^, using `for` -instead of `while`: -[source,javascript] ----- var result = 1; for (var counter = 0; counter < 10; counter = counter + 1) - result = result * 2; + result = result * 2; console.log(result); // → 1024 ----- +Yha hum for loop ke aage {} brackets nahi laga rahe hai iski jagah hum 2 space diye hue hai isse hume ye janane mei asani hogi ki for loop kha se start hua hai ,aisa hum tab karte hai jab hume for loop mei keval ek statement dalni hai {} brackets na lagana matlab for loop mie keval ek statement hai. + -(((programming style)))(((indentation)))Note that even though no block -is opened with a `{`, the statement in the loop is still indented two -spaces to make it clear that it “belongs” to the line before it. -== Breaking Out of a Loop == -(((loop,termination of)))(((break keyword)))Having the loop's -condition produce `false` is not the only way a loop can finish. There -is a special statement called `break` that has the effect of -immediately jumping out of the enclosing loop. -This program illustrates the `break` statement. It finds the first number -that is both greater than or equal to 20 and divisible by 7. +Breaking Out of a Loop + +Jab loop ki condition false ho jati hai tab hum loop se bahar aa jate hai, jisse loop band ho jata hai. Socho agar aapko loop se bahar aana hai aur wo bhi bina condition ko false kiye to iske liye hum break statement ka use karte hai.loop ke ander break likhne se hum loop se directly jump karke bahar aa jate hai. +Yeh program break statement ke use ko describe karta hai,ki break statement ka use hum kaise karte hai.Ismei hume 20 ya 20 ke bad pehle jo number 7 se divide hote hai wo print karne hai. -[source,javascript] ----- for (var current = 20; ; current++) { if (current % 7 == 0) break; } console.log(current); // → 21 ----- - -(((remainder operator)))(((% operator)))Using the remainder -(`%`) operator is an easy way to test whether a number is divisible by -another number. If it is, the remainder of their division is zero. +Hum modulus (%) ka use karke asani se yeh pta laga sakte hai ki koi number dusre number se divide ho rha hai ya nahi. Agar unke division ka remainder zero aayega tab wo number dusre se divide ho raha hoga. Jaise uppar wale example mei koi bhi aise part nahi hai jo loop ko finish kare matlab loop mai koi bhi esi condition nhi hai jo false ho, isme tab tak loop stop nahi hoga jab tak hum break statement nahi lagayenge. -(((for loop)))The `for` construct in the example does not have a part -that checks for the end of the loop. This means that the loop will -never stop unless the `break` statement inside is executed. -If you were to leave out that `break` statement or accidentally write -a condition that always produces `true`, your program would get stuck -in an _((infinite loop))_. A program stuck in an infinite loop will -never finish running, which is usually a bad thing. +Agar apne koi esa program likha hai jisme kabhi bhi condtion false nhi ho rahi hai aur apne break statement bhi nhi lagai to socho kya hoga ? +To apka program infinite ho jayega jiska matlab aapka program kabhi finish nhi hoga chalta rahega, joh ki buri chij hai. -ifdef::interactive_target[] -If you create an infinite loop in one of the examples on these pages, -you'll usually be asked whether you want to stop the script after a -few seconds. If that fails, you will have to close the tab that you're -working in, or on some browsers close your whole browser, in order to -recover. +Agar apne iss page ke ek example mei infinite loop chala diya aur bad mei aap usse band karna chahenge to aisa karne ke liye jiss page pe aap kam kar rahe ho wo apko close karna padega. ya fir recover karne ke liye apko pure browser ko hi band karna pad sakta hai.aisa isliye ho raha hai kyuki browser ka har part ek dusre se link hota hai. Jab aap page par infinite loop chalaoge to wo page hang ho jayega kyuki loop ka koi end nahi millega. Jab ek page hang ho gaya to dusre pages automatically hang ho jayenge. Kyuki sare pages aapas mei connected hote hai. -endif::interactive_target[] +Jaise break keyword hota hai thik aise hi ek continue keyword hota hai jo loop ki progress ko effect karta hai. Agar hum continue keyword ko loop mei dal de to,tab program loop see bahar aakar ,loop ki next iteration se fir se continue karega. -(((continue keyword)))The `continue` keyword is similar to `break`, in -that it influences the progress of a loop. When `continue` is -encountered in a loop body, control jumps out of the body and -continues with the loop's next iteration. -== Updating variables succinctly == +Updating variables succinctly -(((assignment)))(((+= operator)))(((-= operator)))(((/= -operator)))(((*= operator)))(((state)))(((side effect)))Especially -when looping, a program often needs to “update” a variable to hold a -value based on that variable's previous value. - -// test: no - -[source,javascript] ----- +Especially when looping, a program often needs to “update” a variable to hold a value based on that variable’s previous value. +Aapne notice kiya hoga ki loop karte time hume variables ki value change karni padti hai. Jaise, counter = counter + 1; ----- +Javascript hume aisa karne ke liye ek shortcut deti hai : -JavaScript provides a shortcut for this: -// test: no -[source,javascript] ----- counter += 1; ----- -Similar shortcuts work for many other operators, such as `result *= 2` to -double `result` or `counter -= 1` to count downward. +Yeh shortcut aur bhi operators ke saath chalta hai. Jaise, +Counter = counter*2; // shortcut counter *= 2; +Counter = counter -1; //shortcut couner-=1; -This allows us to shorten our counting example a little more. +Pehle example mei her baar counter ki value double ho rahi. Aur dusre mein hum counter ki value her baar 1 se kam kar rahe hai. -[source,javascript] ----- + +Yeh hume upar wale example ko aur short karne me help karta hai , +Inn shortcuts ka use karke hum “even numbers” wale example ka code thoda chota kar sakte hai : for (var number = 0; number <= 12; number += 2) console.log(number); ----- -(((++ operator)))(((-- operator)))For `counter += 1` and `counter -= -1`, there are even shorter equivalents: `counter++` and `counter--`. -== Dispatching on a value with switch == +Javascript mein counter += 1 likhne ka bhi shortcut hota hai. “Counter++”. Issi tarah counter -= 1 ko hum “counter--” likh sakte hai. Generally, counter++ aur counter-- use kiya jata hai.It is common for code to look like this:: counter++ and counter--. + -(((syntax)))(((conditional execution)))(((dispatching)))(((if -keyword,chaining)))It is common for code to look like this: -// test: no +Dispatching on a value with switch -[source,javascript] ----- -if (variable == "value1") action1(); +It is common for code to look like this:Aksar aisa hota hai ki hume variable ki value 3-4 values se compare karni padti hai. Aur fir decision lena hota hai. Aisa karne ke liye hum ek se jyada if/else ka use karte hai.Aur humara code kuch aisa dikhta hai :if (variable == "value1") action1(); else if (variable == "value2") action2(); else if (variable == "value3") action3(); else defaultAction(); ----- +Aisa hum “switch” keyword ka use karke bhi kar sakte hai. Jaise,switch( variable ) { + case “value1”: + action1(); + break; + case “value2”: + action2(); + break; + case “value3”: + action3(); + break; + Default: + defaultAction(); + Break; +} +Switch ke baad hum jiss variable ki value hume compare karni hai, wo likhte hai. Aur switch ka “block” start karte hai. Jinn bhi values se hum variable ki value compare karna chahte hai, unn values ko hum “case” keyword ke baad likhte hai. Switch ke andar hum kitne bhi “case” bana sakte hai. Hum ek “default” keyword bhi use karte hai. Iska code tab execute hota hai jab variable ki value kissi aur value se match nhi hoti. +Control flow uss case par jata hai jahan variable ki value match hoti hai. Aur uske neeche likhe code ko “break” keyword tak execute karta hai. Jaise hi break aata hai control flow switch block se nikal jata hai. Example, + -(((colon character)))(((switch keyword)))There is a construct called -`switch` that is intended to solve such a “dispatch” in a more direct -way. Unfortunately, the syntax JavaScript uses for this (which it -inherited from the C/Java line of programming languages) is somewhat -awkward—a chain of `if` statements often looks better. Here is an -example: -[source,javascript] ----- switch (prompt("What is the weather like?")) { case "rainy": console.log("Remember to bring an umbrella."); @@ -750,69 +378,43 @@ switch (prompt("What is the weather like?")) { console.log("Unknown weather type!"); break; } ----- - -(((fallthrough)))(((comparison)))(((break keyword)))(((case -keyword)))(((default keyword)))You may put any number of `case` labels -inside the block opened by `switch`. The program will jump to the -label that corresponds to the value that `switch` was given or to -`default` if no matching value is found. It starts executing -statements there, even if they're under another label, until it -reaches a `break` statement. In some cases, such as the `"sunny"` case -in the example, this can be used to share some code between cases (it -recommends going outside for both sunny and cloudy weather). But -beware: it is easy to forget such a `break`, which will cause the -program to execute code you do not want executed. - -== Capitalization == - -(((capitalization)))(((variable,naming)))(((whitespace)))Variable -names may not contain spaces, yet it is often helpful to use multiple -words to clearly describe what the variable represents. These are -pretty much your choices for writing a variable name with several -words in it: - ----- -fuzzylittleturtle -fuzzy_little_turtle -FuzzyLittleTurtle -fuzzyLittleTurtle ----- - -(((camel case)))(((programming style)))(((underscore character)))The -first style can be hard to read. Personally, I like the look of the -underscores, though that style is a little painful to type. The -((standard)) JavaScript functions, and most JavaScript programmers, -follow the bottom style—they capitalize every word except the first. -It is not hard to get used to little things like that, and code with -mixed naming styles can be jarring to read, so we will just follow -this ((convention)). - -(((Number function)))(((constructor)))In a few cases, such as the -`Number` function, the first letter of a variable is also capitalized. -This was done to mark this function as a constructor. What a -constructor is will become clear in -link:06_object.html#constructors[Chapter 6]. For now, the important -thing is not to be bothered by this apparent lack of ((consistency)). - -== Comments == - -(((readability)))Often, raw code does not convey all the information -you want a program to convey to human readers, or it conveys it in -such a cryptic way that people might not understand it. At other -times, you might just feel poetic or want to include some thoughts as -part of your program. This is what _((comment))s_ are for. - -(((slash character)))(((line comment)))A comment is a piece of text -that is part of a program but is completely ignored by the computer. -JavaScript has two ways of writing comments. To write a single-line -comment, you can use two slash characters (`//`) and then the comment -text after it. - -// test: no - -[source,javascript] ----- + + + +switch (prompt("Aaj konsa day hai?")) { + case "Saturday": + console.log("Scooter saaf karna hai"); + case "Sunday": + console.log("Office ki holiday hai"); + break; + default: + console.log("Saturday/Sunday nhi hai"); + break; +} + +Iss example mein agar user “Saturday” input karega, tab “scooter saaf karna hai” aur “office ki holiday hai” console per print hoga. Aisa isliye hoga kyunki case value match hone ke baad code break statement tak execute hota hai. Isliye case “sunday” ka bhi code execute ho jayega. Aisa karke hum 2 cases, “saturday” aur “sunday” ka code share kar sakte hai. Magar, aise karte hue humesha dhyan rakhe kyunki kabhi-kabhar jo code aap execute karna nhi chahte wo bhi galti se execute ho jayega. + + +Capitalization + +Variable name mei hum space nahi dal sakte jabki bhut sare word ko alag aur clear tarike se padne k liye hum space dalte hai lekin yeh valid nahi hai.aisa karne ke liye aap underscore(“_”)ka use kar sakte hai.jaise yeh example dekho: Generally, agar kissi naam mein ek se jyada words hote hai to hum usse space se separate kar dete hai. Jaise, pankaj kumar. Magar variable ke naam mein spaces nhi aa sakte. +Agar variable ke naam mein ek se jyada word ho to hum usse neeche gaye teen tareekon mein se kissi bhi ek tareeke se likh sakte hai. Jaise, + +pankajkumar +pura naam without spaces +pankaj_kumar +her word ke beech mein underscore +pankajKumar +pehle word small mein, uske baad her word ka pehla letter capital +Pehle tareeke se jyada lambe variables ke naam samajh nhi aate. Dusre tareeke mein hume bar-bar underscore use karna padta hai. Aur, teesra tareeka bhaur se javascript programmers aur standard javascript functions use karte hai. Aapko shuruaat mein aise variable ka naam type karne mein problem hogi. Magar, aisa karne se aapko apna code padne mein aasani hogi. + + + +Comments + +Aapne notice kiya hogi ki mein bhaut saare examples mein “do slashes”( // ) use karke text likhta hun. Aisa karne se javascript uss line ko “comment” maanti hai. Comments mein likha koi code ya text execute nhi hota. Agar hum kuch bhi comments mein likhte hai, javascript uss text ko ignore karti hai. Comments ka use karke hum apne code ka meaning aur ache se explain kar sakte hai. Isliye mein bhi apne programs mein comments ka use karta hun. +Javascript mein 2 tareeke se comment kar sakte hai. Pehla, “single line comment” yaani ke “ ek line ka comment”. Agar hum kissi text ki shuruaat mein // likh dete hai. To wo text, single line comment ban jaata hai. Jaise, + var accountBalance = calculateBalance(account); // It's a green hollow where a river sings accountBalance.adjust(); @@ -821,15 +423,10 @@ var report = new Report(); // Where the sun on the proud mountain rings: addToReport(accountBalance, report); // It's a little valley, foaming like light in a glass. ----- -(((block comment)))A `//` comment goes only to the end of the line. A -section of text between `/*` and `*/` will be ignored, regardless of -whether it contains line breaks. This is often useful for adding -blocks of information about a file or a chunk of program. +Aur dusra tarika hai “multi line comment” yaani ke “ek se jyada line ka comment”. Iss tareeke se hum bhut sari line ek sath comment kar sakte hai. Jahan se aapko comment shuru karna hai wahan /* type karo. Aur jahan khatam karna hai wahan */. Multi line comments pure page jitne bhi ho sakte hai. Jaise, + -[source,javascript] ----- /* I first found this number scrawled on the back of one of my notebooks a few years ago. Since then, it has often @@ -838,52 +435,30 @@ blocks of information about a file or a chunk of program. me, so I've decided to keep it. */ var myNumber = 11213; ----- -== Summary == -You now know that a program is built out of statements, which -themselves sometimes contain more statements. Statements tend to -contain expressions, which themselves can be built out of smaller -expressions. +Summary + +Ab aap yeh jaan gaye hai ki ek program mein bhot saari statements hoti hai, statement mei ek se jyada expression ho sakte hai. Aur, yeh expressions bhi apne jaise chote-chote expressions se bante hai. +Generally, statements upar se neeche ki taraf execute hoti hai. Magar hum iss control flow ko “if, else, switch, while, do while, for aur break” ka use karke change kar sakte hai. + + +Functions mein code likha hota hai jisse hum function ko call karke use kar sakte hai. Function ko call karne ke liye hum function_ka_naam( argument1, argument2 … ) likhte hai. Function calls expression hoti hai. Aur yeh kabhi-kabhar value bhi return karti hai. -Putting statements after one another gives you a program that is -executed from top to bottom. You can introduce disturbances in the -flow of control by using conditional (`if`, `else`, and `switch`) and -looping (`while`, `do`, and `for`) statements. -Variables can be used to file pieces of data under a name, and they -are useful for tracking state in your program. The environment is the -set of variables that are defined. JavaScript systems -always put a number of useful standard variables into your -environment. -Functions are special values that encapsulate a piece of program. You -can invoke them by writing `functionName(argument1, argument2)`. Such -a function call is an expression, and may produce a value. -== Exercises == -(((exercises)))If you are unsure how to try your solutions to -exercises, refer to the link:00_intro.html#intro[introduction]. +Exercises -Each exercise starts with a problem description. Read that and try to -solve the exercise. If you run into problems, consider reading the -hints (!interactive after the exercise!)(!book at the link:hints.html#hints[end of the book]!). -Full solutions to the exercises are not included in this -book, but you can find them online at -http://eloquentjavascript.net/code[_eloquentjavascript.net/code_]. -If you want to learn something from the exercises, I recommend looking -at the solutions only after you've solved the exercise, or at least -after you've attacked it long and hard enough to have a slight -headache. +If you are unsure how to try your solutions to exercises, refer to the introduction. -=== Looping a triangle === +Her exercise mein bataya gaya hai ki aapko kya karna hai. Usse ek baar pehle padho aur try karo solve karne ka. Agar, samajh nhi aata ki exercise kaise karni hai, to uske neeche diye gaye hints ko padhe. Exercises ke solution aap iss link par dekh sakte hai. Agar aap sahi mein kuch seekhna chahte ho, to pehle exercise khud solve karna aur fir solution dekhna. Ya tab solution dekhna jab exercise aapko ache se pareshaan kar de. -(((triangle (exercise))))Write a ((loop)) that makes seven calls to -`console.log` to output the following triangle: ----- +Looping a triangle + +Aisa ek loop likhe jo console.log function ko 7 baar call kare. Aur aisa triangle output kare: # ## ### @@ -891,142 +466,33 @@ headache. ##### ###### ####### ----- - -It may be useful to know that you can find the length of a string by -writing `.length` after it. -[source,javascript] ----- +Hint: Aap ek string ki length yaani ke uss string mein kitne characters hai, uske naam ke aage .length likh kar nikal sakte ho. var abc = "abc"; console.log(abc.length); // → 3 ----- - -ifdef::interactive_target[] - -Most exercises contain a piece of code that you can modify to solve -the exercise. Remember that you can click code blocks to edit them. - -[source,javascript] ----- -// Your code here. ----- -endif::interactive_target[] - -!!hint!! - -(((triangle (exercise))))You can start with a program that simply -prints out the numbers 1 to 7, which you can derive by making a few -modifications to the -link:02_program_structure.html#loops[even number printing example] -given earlier in the chapter, where the `for` loop was introduced. - -Now consider the equivalence between numbers and strings of hash -characters. You can go from 1 to 2 by adding 1 (`+= 1`). You can go -from `"#"` to `"##"` by adding a character (`+= "#"`). Thus, your -solution can closely follow the number-printing program. +Bahut sari exercise mei code ka ek chota sa piece hai jise aap modify karke solve kar sakte hai ,isse aap kisi code ko aasani ye smajh sakte hai .ye yad rakhe ki code block par click karne se aap usmei edit kar sakte hai -!!hint!! -=== FizzBuzz === -(((FizzBuzz (exercise))))(((loop)))(((conditional execution)))Write a -program that uses `console.log` to print all the numbers from 1 to -100, with two exceptions. For numbers divisible by 3, print `"Fizz"` -instead of the number, and for numbers divisible by 5 (and not 3), -print `"Buzz"` instead. -When you have that working, modify your program to print `"FizzBuzz"`, -for numbers that are divisible by both 3 and 5 (and still print -`"Fizz"` or `"Buzz"` for numbers divisible by only one of those). +JavaScript -(This is actually an ((interview question)) that has been claimed to -weed out a significant percentage of programmer candidates. So if you -solved it, you're now allowed to feel good about yourself.) +Ek program banao jo 1 se 100 tak numbers print kare. Magar, agar number 3 se divisible hai to “java” print hona chaiye. Aur agar number 5 se divisible hai to “script” print hona chahiye. Warna wo number print hona chahiye. +Yeh program banane ke baad, iss program ko change kar kar “JavaScript” print karao agar number 3 aur 5 dono se divisible hai. Dhyan rakhe ki jo kaam program pehle kar raha tha, wo ab bhi hona chahiye. +( Yeh question bhot se interviews mein pucha gaya hai. Aur kaafi log isse solve nhi kar paate. … ? -ifdef::interactive_target[] -[source,javascript] ----- -// Your code here. ----- -endif::interactive_target[] -!!hint!! +Chess board -(((FizzBuzz (exercise))))(((remainder operator)))(((% operator)))Going -over the numbers is clearly a looping job, and selecting what to print -is a matter of conditional execution. Remember the trick of using the -remainder (`%`) operator for checking whether a number is divisible by -another number (has a remainder of zero). +Ek aisa program likho jo ek string creat kare aur wo string 8*8 grid represent kare matlab 8 8 aisi lines bnani chahiye jo aaps mei intersect ho jaise chess ke box hote hai.aur hume har ek box ki position par hume space ya “#” character likhna hai.To inn character se ek chess board banana chahiye.jab hum inn string value ko console.log mei chla kar dekhe to hume ye output mile-- -In the first version, there are three possible outcomes for every -number, so you'll have to create an `if`/`else if`/`else` chain. - -(((|| operator)))(((if keyword,chaining)))The second version of the -program has a straightforward solution and a clever one. The simple -way is to add another “branch” to precisely test the given condition. -For the clever method, build up a string containing the word or words -to output, and print either this word or the number if there is no -word, potentially by making elegant use of the `||` operator. - -!!hint!! - -=== Chess board === - -(((chess board (exercise))))(((loop)))(((nesting,of loops)))(((newline -character)))Write a program that creates a string that represents an -8×8 grid, using newline characters to separate lines. At each position -of the grid there is either a space or a “#” character. The characters -should form a chess board. - -Passing this string to `console.log` should show something like this: - ----- - # # # # -# # # # +# # # # +# # # # # # # # -# # # # +# # # # # # # # -# # # # +# # # # # # # # -# # # # ----- - -When you have a program that generates this pattern, define a -((variable)) `size = 8` and change the program so that it works for -any `size`, outputting a grid of the given width and height. - -ifdef::interactive_target[] -[source,javascript] ----- -// Your code here. ----- -endif::interactive_target[] - -!!hint!! - -(((chess board (exercise))))The string can be built by starting with -an empty one (`""`) and repeatedly adding characters. A newline -character is written `"\n"`. - -Use `console.log` to inspect the output of your program. - -(((nesting,of loops)))To work with two ((dimensions)), you will need a -((loop)) inside of a loop. Put ((curly braces)) around the bodies of -both loops to make it easy to see where they start and end. Try to -properly indent these bodies. The order of the loops must follow the -order in which we build up the string (line by line, left to right, -top to bottom). So the outer loop handles the lines and the inner loop -handles the characters on a line. - -(((counter variable)))(((remainder operator)))(((% operator)))You'll -need two variables to track your progress. To know whether to put a -space or a hash sign at a given position, you could test whether the -sum of the two counters is even (`% 2`). - -Terminating a line by adding a newline character happens after the -line has been built up, so do this after the inner loop but inside of -the outer loop. - -!!hint!! +# # # # +Jab apke pass isss upper wale pattern ko generate karne ka program hoga ,aise hi ek variable size = 8 defined karo aur program tab bhi chlana chahiye jab size ki value kuch bhi ho. \ No newline at end of file diff --git a/04_data.txt b/04_data.txt index fd9e77b00..b307678e2 100644 --- a/04_data.txt +++ b/04_data.txt @@ -14,7 +14,6 @@ Mr. Babbage, if you put into the machine wrong figures, will the right answers come out?’ [...] I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question. ____ - (((Babbage+++,+++ Charles)))(((object)))(((data structure)))Numbers, Booleans, and strings are the bricks that ((data)) structures are built from. But you can't make much of a house out of a single brick. _Objects_ allow us to group diff --git a/05_higher_order.txt b/05_higher_order.txt index ef6edb5ed..e29c4c402 100644 --- a/05_higher_order.txt +++ b/05_higher_order.txt @@ -1,33 +1,5 @@ -:chap_num: 5 -:prev_link: 04_data -:next_link: 06_object -:load_files: ["code/ancestry.js", "code/chapter/05_higher_order.js", "code/intro.js"] -:zip: node/html - -= Higher-Order Functions = - -ifdef::interactive_target[] - -[chapterquote="true"] -[quote, Master Yuan-Ma, The Book of Programming] -____ -Tzu-li and Tzu-ssu were -boasting about the size of their latest programs. ‘Two-hundred -thousand lines,’ said Tzu-li, ‘not counting comments!’ Tzu-ssu -responded, ‘Pssh, mine is almost a *million* lines already.’ Master -Yuan-Ma said, ‘My best program has five hundred lines.’ Hearing this, -Tzu-li and Tzu-ssu were enlightened. -____ - -endif::interactive_target[] - -[chapterquote="true"] -[quote, C.A.R. Hoare, 1980 ACM Turing Award Lecture] -____ -(((Hoare+++,+++ C.A.R.)))There are two ways of constructing a software -design: One way is to make it so simple that there are obviously no -deficiencies, and the other way is to make it so complicated that -there are no obvious deficiencies. +Chapter 5 +Higher-Order Functions[quote, Master Yuan-Ma, The Book of Programming] ____ (((program size)))A large program is a costly program, and not just @@ -37,6 +9,19 @@ programmers, in turn, tend to introduce mistakes (_((bug))s_) into programs. A large program also provides a lot of space for these bugs to hide, making them hard to find. + +///** HINDI **// + +(((prograam aakaar))) ek bada kaaryakram mahanga kaaryakram +hai, na ki bas kyonki us samay ke nirmaan ke lie leta hai aakaar lagabhag +hamesha shaamil hota hai (jatilata)), aur jatilata prograamar ko bhramit +karatee hai pareshaan prograamar, badale mein, galatiyon ko shuroo karate hain +(_ ((bag)) s_) mein kaaryakram. ek bada kaaryakram in bagon ke lie bahut saare +sthaan pradaan karata hai chhupaane ke lie, unhen khojane ke lie mushkil bana +rahee hai + + + (((summing example)))Let's briefly go back to the final two example programs in the introduction. The first is self-contained and six lines long. diff --git a/07_elife.txt b/07_elife.txt index be35381f8..b6daf65ed 100644 --- a/07_elife.txt +++ b/07_elife.txt @@ -14,17 +14,23 @@ relevant as the question of whether Submarines Can Swim. ____ (((artificial intelligence)))(((Dijkstra+++,+++ Edsger)))(((project -chapter)))(((reading code)))(((writing code)))In “project” chapters, +chapter)))(((reading code)))(((writing code))) +In “project” chapters, I'll stop pummeling you with new theory for a brief moment and instead work through a program with you. Theory is indispensable when learning to program, but it should be accompanied by reading and understanding nontrivial programs. - (((artificial life)))(((electronic life)))(((ecosystem)))Our project in this chapter is to build a virtual ecosystem, a little world populated with ((critter))s that move around and struggle for survival. + +//** HINDI **// +Project chapter mein hum theory pe kam karne ki bejaye direct program pe kam karenge.Theory bahut important hai program likhne k liye lekin jab hum bahut sare alag alag mushkil mushkil program ko padte hai aur smjhte hai tab hum theory ko ache se smjh pate hia aur program likh pate hai. +Iss chapter mei ek virtual ecosystem build karna ya banana humara project hai.Iss chote se world mei bahut sare animals aise hi ghum rhe hai aur apni life jeene k liye struggle kar rhe hai. + +__________________________________________________________________________________________finish == Definition == (((dimensions)))(((electronic life)))To make this @@ -32,17 +38,22 @@ task manageable, we will radically simplify the concept of a _((world))_. Namely, a world will be a two-dimensional ((grid)) where each entity takes up one full square of the grid. On every _((turn))_, the critters all get a chance to take some action. - (((discretization)))(((simulation)))Thus, we chop both time and space into units with a fixed size: squares for space and turns for time. Of course, this is a somewhat crude and inaccurate ((approximation)). But our simulation is intended to be amusing, not accurate, so we can freely cut such corners. - [[plan]] (((array)))We can define a world with a _plan_, an array of strings that lays out the world's grid using one character per square. +//** HINDI **// +Iss kam ko manageable banane k liye sbse pehle to hume world word ka pura matlab smjhate hai. +World ek two dimentional shape hai jisme ek full square gridek puri unit ko repersent karta hai.Aur har ek turn par animal ko ek chance milega action lene ka. +To humne yha par time aur spaces ko 2 fixed size units mei devide yani bat dia.pehla square spaces k liye aur turns time k liye.Ha ye ek bekar aur inaccurate approximation hai.Lekin hum bs apne estimation se todi si feel lena chahte hai. +Hum world ko ek plane k jaise represent kar rhe hai.esai socho jaise ek character ka ek lamba sa array hia isko hum world ki grids bhi keh sakte hai. + +__________________________________________________________________________________________finish // include_code [source,javascript] @@ -64,7 +75,6 @@ var plan = ["############################", The “#” characters in this plan represent ((wall))s and rocks, and the “o” characters represent critters. The spaces, as you might have guessed, are empty space. - (((object)))(((toString method)))(((turn)))A plan array can be used to create a ((world)) object. Such an object keeps track of the size and content of the world. It has a `toString` method, which @@ -73,6 +83,13 @@ was based on) so that we can see what's going on inside. The world object also has a `turn` method, which allows all the critters in it to take one turn and updates the world to reflect their actions. + + +//** HINDI **// +Iss simple plane mei "#" character diwaro aur paththero ko represent karta hai."o" character animals ko repersent karta hai.Spaces ko aap simple spaces ki tarah man sakte hai. +Ek plan array (list) se hum ek object bna sakte hai.wo object world k size aur content ko define karega.Iske liye 'toString' method hota hai jo world ko print hone wale strings mei convert kar deta hai.jisse hum aaram se smjh sakte hai ki kya chl rha hai.World object k pass ek 'turn' method bhi hota hai jo animals ko ek bar turn aur world ko update karne ki permission deta hia. + +__________________________________________________________________________________________finish [[grid]] == Representing space == @@ -83,6 +100,9 @@ identified by their x- and y-coordinates. We use a simple type, link:06_object.html#exercise_vector[previous chapter]), to represent these coordinate pairs. +//** HINDI **// +World object ek model hota hai jiski width and height fixed hoti hia.squares ko hum x-axis and y-axis se measure kar sakte hai. +___________________________________________________________________________________________finish // include_code [source,javascript] @@ -101,7 +121,6 @@ models the grid itself. A grid is part of a world, but we are making it a separate object (which will be a property of a ((world)) object) to keep the world object itself simple. The world should concern itself with world-related things, and the grid should concern itself with grid-related things. - (((array)))(((data structure)))To store a grid of values, we have several options. We can use an array of row arrays and use two property accesses to get to a specific square, like this: @@ -118,6 +137,12 @@ console.log(grid[1][2]); single array, with size width × height, and decide that the element at (_x_,_y_) is found at position _x_ + (_y_ × width) in the array. + +//** HINDI **// +Ab hume models grid ka object type pta karna hai.Grid ek world ka chota sa part hai lekin hum isko ek alag object manenge jisse world ko hum alag man sake.world apne aap ko world se related cheezo se relate karna chahiye thik ussi tarah grid bhi apne se related cheezo se relate karna chahiye. +Grid ki value store karne ka liye humare pass bahut sare option hai.hum 2 arrays ki ek array ko use kark bhi square ki specifice property ko access kar sakte hai jaise humne niche kia hai. +Iske alawa hum single array bhi use kar sakte hai, jiska size width * height hoga, aur fir hume array ka koi bhi lena hai to hum _x_ + (_y_ * width) ka use karenge. + [source,javascript] ---- var grid = ["top left", "top middle", "top right", @@ -125,6 +150,7 @@ var grid = ["top left", "top middle", "top right", console.log(grid[2 + (1 * 3)]); // → bottom right ---- +_________________________________________________________________________________________________finish (((encapsulation)))(((abstraction)))(((Array constructor)))(((array,creation)))(((array,length of)))Since the actual access to this array will be wrapped in methods @@ -137,6 +163,12 @@ array of the given length. (((Grid type)))This code defines the `Grid` object, with some basic methods: +//** HINDI **// +Iss array k elements ko access karne methods grid object type mei milte hia.ye important nhi hai ki hum kon sa method use kare.Yha hum second method choose karenge kyuki usse hum asani se array bna sakte hai. + +Ye niche diya gya code grid object ko smjhata hai aur uske kuch basics methods k bare mei btata hai:- +_________________________________________________________________________________________________finish + // include_code [source,javascript] @@ -159,7 +191,9 @@ Grid.prototype.set = function(vector, value) { ---- And here is a trivial test: - +//**HINDI**// +Ab ye toda mushkil aur alag trike ka test hoga +_________________________________________________________________________________________________finish [source,javascript] ---- var grid = new Grid(5, 5); @@ -182,6 +216,11 @@ that, when called, returns an _action_. An action is an object with a take, for example `"move"`. The action may also contain extra information, such as the direction the critter wants to move in. + + +//**HINDI**// + + [[directions]] (((Vector type)))(((View type)))(((directions object)))(((object,as map)))Critters are terribly myopic and can see only the squares directly around them on the grid. But even this limited vision From 44097cd18ceac345adec4b467c687508c1efea90 Mon Sep 17 00:00:00 2001 From: courage Date: Tue, 5 Sep 2017 01:46:45 +0530 Subject: [PATCH 02/22] Translate 4 chapter --- 04_data.txt | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/04_data.txt b/04_data.txt index fd9e77b00..afa8fb211 100644 --- a/04_data.txt +++ b/04_data.txt @@ -13,25 +13,49 @@ On two occasions I have been asked, ‘Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out?’ [...] I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question. + + mujhe do avsaron pe pucha gaya prarthana krne kleay +Mr. Babbage, yadi aap masheen mei galat aankade daalate hain, to sahee +javaab hokar nikalate hain? [...] main is tarah kee jaanakaaree ko haasil karane mein saksham nahin hoon +aise vichaaron ke bhram kee vajah se jo is tarah ke savaal ko bhadak saken ____ + + (((Babbage+++,+++ Charles)))(((object)))(((data structure)))Numbers, Booleans, and strings are the bricks that ((data)) structures are built from. But you can't make much of a house out of a single brick. _Objects_ allow us to group values—including other objects—together and thus build more complex structures. +(((Babbage+++,+++ Charles)))(((object)))(((data structure)))nambar, booliyan, aur strings hain +eeton ki ((data)) dhache se bana hain lekin aap nahin bana sakte +ek eent mein se adhik ek ghar _objects_ hamen group ke liye anumati deta hai +or vastuon sahit objects—together aur is prakaar adhik jatil structures banaate hain. + + The programs we have built so far have been seriously hampered by the fact that they were operating only on simple data types. This chapter will add a basic understanding of data structures to your toolkit. By the end of it, you'll know enough to start writing some useful programs. +ab tak hamane jo programs banae hain, use gambheerata se baadhit kiya gaya hai +fact yah hai ki ve keval saral data types par kaam kar rahe the. yah chapter +aapake basic mein data structures kee toolkit samajh ke jod dega. dvaara +isake last mein, aap kuchh upayogee likhana shuroo karane ke lie useful programs jaanate honge. + The chapter will work through a more or less realistic programming example, introducing concepts as they apply to the problem at hand. The example code will often build on functions and variables that were introduced earlier in the text. +Chapter adhik ya kam prograaming ke maadhyam se kaam karega +example ke liye, introducing ko present karana kyonki ve samasya par haath mein lage hote hain. +Jo example hain wo code function aur veriebal build karta hain par banaayega jo ki the +pahale paath mein introduced kiya hain. + + ifdef::book_target[] (((sandbox)))The online coding sandbox for the book From 614738a51b41de50e436e01e617d7521b128008c Mon Sep 17 00:00:00 2001 From: dhannukumar Date: Tue, 5 Sep 2017 02:39:09 +0530 Subject: [PATCH 03/22] 4 chapter --- 04_data.txt | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/04_data.txt b/04_data.txt index fd9e77b00..7de6a8ada 100644 --- a/04_data.txt +++ b/04_data.txt @@ -13,6 +13,11 @@ On two occasions I have been asked, ‘Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out?’ [...] I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question. +# +mujhe do avsaron pe pucha gaya prarthana krne kleay +Mr. Babbage, yadi aap masheen mei galat aankade daalate hain, to sahee +javaab hokar nikalate hain? [...] main is tarah kee jaanakaaree ko haasil karane mein saksham nahin hoon +aise vichaaron ke bhram kee vajah se jo is tarah ke savaal ko bhadak saken ____ (((Babbage+++,+++ Charles)))(((object)))(((data structure)))Numbers, Booleans, and strings are the @@ -20,17 +25,32 @@ bricks that ((data)) structures are built from. But you can't make much of a house out of a single brick. _Objects_ allow us to group values—including other objects—together and thus build more complex structures. +# +(((Babbage+++,+++ Charles)))(((object)))(((data structure)))nambar, booliyan, aur strings hain +eeton ki ((data)) dhache se bana hain lekin aap nahin bana sakte +ek eent mein se adhik ek ghar _objects_ hamen group ke liye anumati deta hai +or vastuon sahit objects—together aur is prakaar adhik jatil structures banaate hain The programs we have built so far have been seriously hampered by the fact that they were operating only on simple data types. This chapter will add a basic understanding of data structures to your toolkit. By the end of it, you'll know enough to start writing some useful programs. +# +ab tak hamane jo programs banae hain, use gambheerata se baadhit kiya gaya hai +fact yah hai ki ve keval saral data types par kaam kar rahe the. yah chapter +aapake basic mein data structures kee toolkit samajh ke jod dega. dvaara +isake last mein, aap kuchh upayogee likhana shuroo karane ke lie useful programs jaanate honge The chapter will work through a more or less realistic programming example, introducing concepts as they apply to the problem at hand. The example code will often build on functions and variables that were introduced earlier in the text. +# +Chapter adhik ya kam prograaming ke maadhyam se kaam karega +example ke liye, introducing ko present karana kyonki ve samasya par haath mein lage hote hain. +Jo example hain wo code function aur veriebal build karta hain par banaayega jo ki the +pahale paath mein introduced kiya hain. ifdef::book_target[] From 717a6c22051e8af35ea04d23d9a346730495cad8 Mon Sep 17 00:00:00 2001 From: shivam8800 Date: Tue, 5 Sep 2017 03:31:28 +0530 Subject: [PATCH 04/22] starting translate chapter 3 --- 03_functions.txt | 1002 +++++----------------------------------------- 04_data.txt | 27 +- 2 files changed, 97 insertions(+), 932 deletions(-) diff --git a/03_functions.txt b/03_functions.txt index d7aed41bb..00e773a9e 100644 --- a/03_functions.txt +++ b/03_functions.txt @@ -1,70 +1,40 @@ -:chap_num: 3 -:prev_link: 02_program_structure -:next_link: 04_data - -= Functions = - -[chapterquote="true"] -[quote, Donald Knuth] -____ -People think that computer science is the art of -geniuses but the actual reality is the opposite, just many people -doing things that build on each other, like a wall of mini stones. -____ - -(((Knuth+++,+++ Donald)))(((function)))(((code structure)))You've seen function values, such -as `alert`, and how to call them. Functions are the bread and butter -of JavaScript programming. The concept of wrapping a piece of program -in a value has many uses. It is a tool to structure larger programs, -to reduce repetition, to associate names with subprograms, and to -isolate these subprograms from each other. - -(((human language)))The most obvious application of functions is -defining new ((vocabulary)). Creating new words in regular, -human-language prose is usually bad style. But in programming, it is -indispensable. - -(((abstraction)))Typical adult English speakers have some 20,000 words -in their vocabulary. Few programming languages come with 20,000 -commands built in. And the vocabulary that _is_ available tends to be -more precisely defined, and thus less flexible, than in human -language. Therefore, we usually _have_ to add some of our own -vocabulary to avoid repeating ourselves too much. - -== Defining a function == - -(((square)))(((function,definition)))A function definition is just a -regular ((variable)) definition where the value given to the variable -happens to be a function. For example, the following code defines the -variable `square` to refer to a function that produces the square of a -given number: - -[source,javascript] ----- +Chapter 3 +program structure + +Functions + +{ + Bohut se log yeh sochte hai ki computer science geniuse logo ka kam hai, par reality me esa nhi hai. Jaise bund bund se ghada barta hai wese hi + + Donald Knuth + +} + +Jaise ki aapne function dekhe hoge jaise ki alert, aur unko call kaise karte hai. Functions javaScript me bohut important hote hai. Programs ke part ko value me dalkar iske bhot se use kiye ja sakte hai. Yeh bohut acha tarika ka hai kisi bade progaram ko banne ka, or kisi kam ko bar bar karne se bachne ka, aur progarm me apse me jodne ka, aur apas me program ko alag karne ka. + + +Human-language apne ap new words banna jadater sahi nhi hota hai, kyu ki ho sakta hai jo word banya hai uska sahi meaning na nikle ya wo galta ho. Par programing language me esa nhi hai isme apko new words banne ki freedom hai, aur yeh jaruri bhi hai. + + +Jo english speaker ki vocabulary me 20,000 tak words hote hai jo wo use karte hai. Kuch programming languages hai jinme 20,000 tak commands hoti hai. Aur jo vocabulary abhi tend me hai wo theek se define hoti hai, par wo flexible nhi hoti yani uska change kar kr use nhi kiya ja sakta hai. Isliye programing hum khud ke words dal sakte hai taki program me koi koi chij bar bar repeat na ho. + + +Defining a function + +Jaise variable hote hai vaise hi function bhi hote hai ,jaise hum variable ko value dete hai vaise function mei code(value dete hai) likhte hai fir usko hum as a variable kahi bhi use kar sakte hai. For example,ye niche diya hua code ek square nam ke variable mei ek function dalta hai jismei humne kisi ek number ka square return kiya hai: + + var square = function(x) { return x * x; }; - +` console.log(square(12)); // → 144 ----- - -indexsee:[braces,curly braces] -(((curly braces)))(((block)))(((syntax)))(((function -keyword)))(((function,body)))(((function,as value)))A function is -created by an expression that starts with the keyword `function`. -Functions have a set of _((parameter))s_ (in this case, only `x`) and -a _body_, which contains the statements that are to be executed when -the function is called. The function body must always be wrapped in -braces, even when it consists of only a single ((statement)) (as -in the previous example). - -(((power example)))A function can have multiple parameters or no -parameters at all. In the following example, `makeNoise` does not list -any parameter names, whereas `power` lists two: - -[source,javascript] ----- + +Function ek expression represent karta hai , function defined karne ke liye hum uss expresion ke aage “function” keyword lagate hai.function mei parameters(iss case mei x hai) aur body hoti hai,jisko hum function ko call karte time lete hai aur ismei wo statement hoti hai jo execute honi hoti hai.function ki body ko hum braces mei lete hai fir chahe wo singhle statement ho ya double(jaisa humne pichle example mei dekha tha). +Ek Function mei bahut jayada parameters bhi ho sakte hai aur ek bhi parameter nahi bhi ho sakta matalab pure function mei kabhi kabhi paramter hoga hi nahi. + + var makeNoise = function() { console.log("Pling!"); }; @@ -81,49 +51,24 @@ var power = function(base, exponent) { console.log(power(2, 10)); // → 1024 ----- - -(((return value)))(((return keyword)))(((undefined)))Some functions -produce a value, such as `power` and `square`, and some don't, such as -`makeNoise`, which produces only a ((side effect)). A `return` -statement determines the value the function returns. When control -comes across such a statement, it immediately jumps out of the current -function and gives the returned value to the code that called the -function. The `return` keyword without an expression after it will -cause the function to return `undefined`. - -== Parameters and scopes == - -(((function,application)))(((variable,from parameter)))The -((parameter))s to a function behave like regular variables, but their -initial values are given by the _caller_ of the function, not the code -in the function itself. - -(((function,scope)))(((scope)))(((local variable)))An -important property of functions is that the variables created inside -of them, including their parameters, are _local_ to the function. This -means, for example, that the `result` variable in the `power` example -will be newly created every time the function is called, and these -separate incarnations do not interfere with each other. - -indexsee:[top-level scope,global scope] -(((var keyword)))(((global scope)))(((variable,global)))This -“localness” of variables applies only to the parameters and to variables -declared with the `var` keyword inside the function body. Variables -declared outside of any function are called _global_, because they are -visible throughout the program. It is possible to access such -variables from inside a function, as long as you haven't declared a -local variable with the same name. - -(((variable,assignment)))The following code demonstrates this. It -defines and calls two functions that both assign a value to the -variable `x`. The first one declares the variable as local and thus -changes only the local variable. The second does not declare `x` -locally, so references to `x` inside of it refer to the global -variable `x` defined at the top of the example. - -[source,javascript] ----- + +Kuch function aise hote hai jo kuch value produce karte hai jaise yha power aur square function the,aur kuch function koi value produce nahi karte wo keval kuch effect show karta hai jaise yha makeNoise hai.ek return keyword hume ye batata hai ki function kya value dega.jab program return statement par ayega tab wo current function se bahar nikalkar code se jo output niaklta hoga wo output return kar dega.agar return keyword se pehle koi expression nahi hoti to function ki value undefined hogi. + + +Parameters and scopes + +Functions me parameters regular variables ki tarha hote hai, par unki value function me caller se di jati hai, jo value di jati hai woh function me nhi se bhar hoti hai. +Functions ke ander variables banna ek important property hai, jisme parameters bhi sath me ho, yeh sab function ka hi part hai. Example ke liye, power funtion me result variable har bar naya banega jab bhi functon ko call kiya jaega. Functions me jo naye naye variables bante hai wo apas me interface nhi karti hai. + + + +Jo variables ki localness hoti hai yeh sirf parameters aur jo variable var word ke sath declare kiya jate hai unn par lagti hi lagti hai functions ke ander. Jo variables functions ke bhar hote hai unko global bolte hai, kyu ki yeh variables pure program me use kar sakte hai. Aur inko hum functions ke ander bhi use kar sakte hai par agar apke functions me same naam ka variable hai to app isse functions me use nhi kar sakte ho. + + + +Jo niche code hai app isme yeh hi dekhoge. X yaha par hamra global variable hai. Jo pehle aur dusre functions dono me call kiya hai, first me var ka use karte hue x variable ko local variable ki tarah use kiya hai. Isliye jab x ko call kiya hai fuction ke bhar to usme koi change nhi hua jai. Dusre me x ko ek local variable ki tarha declare nhi kiya hai isme x ko goloble varible ki tarah liya hai isliye jab x ki value kari to gobal variabel x ki bhi change ho gai. + + var x = "outside"; var f1 = function() { @@ -134,38 +79,20 @@ console.log(x); // → outside var f2 = function() { - x = "inside f2"; +x = "inside f2"; }; f2(); console.log(x); // → inside f2 ----- - -(((variable,naming)))(((scope)))(((global scope)))(((code,structure -of)))This behavior helps prevent accidental interference between -functions. If all variables were shared by the whole program, it'd -take a lot of effort to make sure no name is ever used for two -different purposes. And if you _did_ reuse a variable name, you might -see strange effects from unrelated code messing with the value of your -variable. By treating function-local variables as existing only within -the function, the language makes it possible to read and understand -functions as small universes, without having to worry about all the -code at once. - -[[scoping]] -== Nested scope == - -(((nesting,of functions)))(((nesting,of -scope)))(((scope)))(((inner function)))(((lexical -scoping)))JavaScript distinguishes not just between _global_ and -_local_ variables. Functions can be created inside other functions, -producing several degrees of locality. - -(((landscape example)))For example, this rather nonsensical function -has two functions inside of it: - -[source,javascript] ----- + + +Yeh behavior se hum ek jaise naam ke bhi variables bana sakte hai. Agar hum ek naam ka ek hi variable bana pae to hame yeh yad rakhna padega ki iss naam ka variable banya na nhi ya ho sakta ha aap galti se same naam ke ek se jada variable bana do alag alag kam ke liye. Aur agar aap use variable ko kahi aur use karte to ho sakta hai ki apko uska result kuch aur hi mile jo use related nhi hai. Isliye hum jab function me local variable ko use karte hai to us local variable ko function ke bhar se koi matlb nhi hota wo sirf uss functions ke liye hi hota hai aur baki chijo ke liye nhi. Language uss function ko padhte time sirf us par hi dayan deti hai use bahar se koi matb nhi hota hai. + + +Nested scope + +javaScript sirf local aur global variables me hi fark nhi dekhata. Aap functions ke ander bhi functions bana sakte ho, isse bhot sare local aur global variable ban jaege, kisi ki liye koi local variable hoga kisi ke liye koi. Jaise ki iss example me, function ke ander do aur functions hai. + var landscape = function() { var result = ""; var flat = function(size) { @@ -178,7 +105,7 @@ var landscape = function() { result += "'"; result += "\\"; }; - + flat(3); mountain(4); flat(6); @@ -187,242 +114,69 @@ var landscape = function() { return result; }; -console.log(landscape()); -// → ___/''''\______/'\_ ----- - -(((function,scope)))(((scope)))The `flat` and `mountain` functions -can “see” the variable called `result`, since they are inside the -function that defines it. But they cannot see each other's `count` -variables since they are outside each other's scope. The environment -outside of the `landscape` function doesn't see any of the variables -defined inside `landscape`. - -In short, each local scope can also see all the local scopes that -contain it. The set of variables visible inside a function is -determined by the place of that function in the program text. All -variables from blocks _around_ a function's definition are -visible—meaning both those in function bodies that enclose it and -those at the top level of the program. This approach to variable -visibility is called _((lexical scoping))_. - -((({} (block))))People who have experience with other programming -languages might expect that any block of code between braces produces -a new local environment. But in JavaScript, functions are the only -things that create a new scope. You are allowed to use free-standing -blocks. - -[source,javascript] ----- -var something = 1; -{ - var something = 2; - // Do stuff with variable something... -} -// Outside of the block again... ----- - -But the `something` inside the block refers to the same variable as -the one outside the block. In fact, although blocks like this are -allowed, they are useful only to group the body of an `if` statement -or a loop. -(((let keyword)))(((ECMAScript 6)))If you find this odd, you're not -alone. The next version of JavaScript will introduce a `let` keyword, -which works like `var` but creates a variable that is local to the -enclosing _block_, not the enclosing _function_. -== Functions as values == +Flat aur mountain funtions, result variable ko use kar sakte hai, kyu ki yeh tino ek hi function ke andar define hai. Par flat or mountain function aapas me ek dusre ke variable use nhi kar sakte hai kyu ki inn dono ko scope alag hai. Landscape ke bhar ka koi bhi function landscape ke andar ka koi bhi variable use nhi kar sakta. -(((function,as value)))Function ((variable))s usually simply act as -names for a specific piece of the program. Such a variable is defined -once and never changed. This makes it easy to start confusing the -function and its name. -(((variable,assignment)))But the two are different. A function value -can do all the things that other values can do—you can use it in -arbitrary ((expression))s, not just call it. It is possible to store a -function value in a new place, pass it as an argument to a function, -and so on. Similarly, a variable that holds a function is still just a -regular variable and can be assigned a new value, like so: +Functions as values -// test: no - -[source,javascript] ----- +Function variable kisi program ke chote part ke naam ko represent karta hai. humne ek variable defined kar diya aur bad mei usko change nahi kiya to, iss function aur iske nam se aap asaani se cofused ho jayenge. +Lekin function aur uske naam alag hai. Ek function ki value wo sab kar sakti hai jo koi dusri karti hai,aap isse kisi bhi expression mei test kar sakte hai.kisi function ki value ek new place mei store karke usmei argument pass kara kara sakte hai.jaise regular variable kuch store karta hai ,aise ek variable banao jo ek function ko store kare aur usmei new value dale,jaise niche dekho -- + var launchMissiles = function(value) { missileSystem.launch("now"); }; if (safeMode) launchMissiles = function(value) {/* do nothing */}; ----- +Aage hum chapter 5 mei iska bahut ache se use karenge,hum waha function ki value function mei dalkar use karnege + + -(((function,higher-order)))In -link:05_higher_order.html#higher_order[Chapter 5], we will discuss the -wonderful things that can be done by passing around function values to -other functions. +Declaration notation -== Declaration notation == +Variable ko defined karne ka short tarika hai “var square = function…” variable ke nam ke aage “var” lagane se variable defined ho jata hai.function ko defined karne ke liye hum function keyword ka use kar sakte hai jisko hum statement ke aage lagate hai, jaise niche likha hua hai-- -(((syntax)))(((square example)))(((function -keyword)))(((function,definition)))(((function,declaration)))There is -a slightly shorter way to say “++var square = function…++”. The -`function` keyword can also be used at the start of a statement, as in -the following: -[source,javascript] ----- function square(x) { return x * x; } ----- +Isse function declaration kahte hai.jaise ye upper wali statement square defined kar rhi hai jisko humne square nam ke variable mei dala hai aur ye variable pure function ki value ko represent kar rha hai.abhi tak to sab thik hai lekin aisi definition mei mei ek exeption hota hai.jaise niche dekhe-- -(((future)))(((execution order)))This is a function _declaration_. The -statement defines the variable `square` and points it at the given -function. So far so good. There is one subtlety with this form of -function definition, however. -[source,javascript] ----- console.log("The future says:", future()); function future() { return "We STILL have no flying cars."; } ----- - -This code works, even though the function is defined _below_ the code -that uses it. This is because function declarations are not part of -the regular top-to-bottom flow of control. They are conceptually moved -to the top of their scope and can be used by all the code in that -scope. This is sometimes useful because it gives us the freedom to -order code in a way that seems meaningful, without worrying about -having to define all functions above their first use. - -(((function,declaration)))What happens when you put such a function -definition inside a conditional (`if`) block or a loop? Well, don't do -that. Different JavaScript platforms in different browsers have -traditionally done different things in that situation, and the latest -((standard)) actually forbids it. If you want your programs to behave -consistently, only use this form of function-defining statements in -the outermost block of a function or program. - -[source,javascript] ----- + +Ye code jo uppper likha hai wo chalega iske bawjud function ki value humne code ke niche likhi hai aisa isliye ho rha hai, kyuki function ki declarations lagatar top to bottom flow of control ka part nahi hota ,hum function ki declaration pure program mei kahi bhi likh sakte hai.basically function declaration ka scop uske upper code tak hota ahi aur iska use hum pure scop mei khai bhi kar sakte hai.kabhi kabhi ye useful hota hai kyuki hum isse program ka flow apne tarike se likh sakte hai ,hum code ko apni understanding ke hossab se bhi likh sakte hai jisse kuch meaningful code ban jaye , isse hume har function ke use se pehle use function ko defined nahi karna padega. + + + +Socho agar hum function ka use conditional statement ke sath use kare to kya hoga? Acha hai magar aisa karna mat.iss situation mei javascript ke alag alag platform alag alag cheeze karte hai aur latest standard isse folow nahi karta. +Agar aap apne programs ko lagatar chalana chalate hai to sirf iss tarah ki function-defining statemment ko apne function ke outermost block mei use kare. + function example() { function a() {} // Okay if (something) { function b() {} // Danger! } } ----- -[[stack]] -== The call stack == -indexsee:[stack,call stack] -(((call stack)))(((function,application)))It will be helpful to take a -closer look at the way control flows through functions. Here is a -simple program that makes a few function calls: +Optional Arguments -[source,javascript] ----- -function greet(who) { - console.log("Hello " + who); -} -greet("Harry"); -console.log("Bye"); ----- - -(((control flow)))(((execution order)))(((console.log)))A run through -this program goes roughly like this: the call to `greet` causes -control to jump to the start of that function (line 2). It calls -`console.log` (a built-in browser function), which takes control, does -its job, and then returns control to line 2. Then it reaches the end -of the `greet` function, so it returns to the place that called it, at -line 4. The line after that calls `console.log` again. - -We could show the flow of control schematically like this: - ----- -top - greet - console.log - greet -top - console.log -top ----- - -(((return keyword)))(((memory)))Because a function has to jump back to -the place of the call when it returns, the computer must remember the -context from which the function was called. In one case, `console.log` -has to jump back to the `greet` function. In the other case, it jumps -back to the end of the program. - -The place where the computer stores this context is the _((call -stack))_. Every time a function is called, the current context is put -on top of this “stack”. When the function returns, it removes the top -context from the stack and uses it to continue execution. - -(((infinite loop)))(((stack overflow)))(((recursion)))Storing this -stack requires space in the computer's memory. When the stack grows -too big, the computer will fail with a message like “out of stack -space” or “too much recursion”. The following code illustrates this by -asking the computer a really hard question, which causes an infinite -back-and-forth between two functions. Rather, it _would_ be infinite, -if the computer had an infinite stack. As it is, we will run out of -space, or “blow the stack”. - -// test: no - -[source,javascript] ----- -function chicken() { - return egg(); -} -function egg() { - return chicken(); -} -console.log(chicken() + " came first."); -// → ?? ----- +Yeh niche wale code ko dekho yeh aaram se bina kisi problem ke execute ho jayega: -== Optional Arguments == - -(((argument)))(((function,application)))The following code is allowed -and executes without any problem: - -[source,javascript] ----- alert("Hello", "Good Evening", "How do you do?"); ----- -(((alert function)))The function `alert` officially accepts only one -argument. Yet when you call it like this, it doesn't complain. It -simply ignores the other arguments and shows you “Hello”. +Officialy ye function keval ek argument accept karta hai.jab aap isko upper wale tarike se call karoge tab koi error to nahi ayegi, bs wo pehle argument ko consider karega aur baki ko ignores kar dega.to iska matlab wo keval “Hello”ka output hi show karega. -(((undefined)))(((parameter)))JavaScript is extremely broad-minded -about the number of arguments you pass to a function. If you pass too -many, the extra ones are ignored. If you pass too few, the missing -parameters simply get assigned the value `undefined`. -The downside of this is that it is possible—likely, even—that you'll -accidentally pass the wrong number of arguments to functions and no -one will tell you about it. +Javascript mei hum jo number argument dete hai,unka hume bahut dhyan rakhna padta hai quki javascript in numbero ko bahut specific tareeke se consider karti hai.agar aapne function mei bahut sare argument de diye to ,javascript unko ignored kar deti hai kaval wo pehle argument ko hi considerd karti hai.Aur agar aapne kuch argument pass nahi kiye to parameter ki value undefined aa jayegi quki aapne us parameter ki value argument mei nahi di. -[[power]] -(((power example)))(((optional argument)))The -upside is that this behavior can be used to have a function take -“optional” arguments. For example, the following version of `power` -can be called either with two arguments or with a single argument, in -which case the exponent is assumed to be two, and the function behaves -like `square`. -// test: wrap - -[source,javascript] ----- function power(base, exponent) { if (exponent == undefined) exponent = 2; @@ -436,36 +190,14 @@ console.log(power(4)); // → 16 console.log(power(4, 3)); // → 64 ----- - -(((console.log)))In the link:04_data.html#arguments_object[next -chapter], we will see a way in which a function body can get at the -exact list of arguments that were passed. This is helpful because it -makes it possible for a function to accept any number of arguments. -For example, `console.log` makes use of this—it outputs all of the -values it is given. - -[source,javascript] ----- -console.log("R", 2, "D", 2); -// → R 2 D 2 ----- - -== Closure == - -(((call stack)))(((local variable)))(((function,as -value)))(((closure)))(((scope)))The ability to treat functions as -values, combined with the fact that local variables are “re-created” -every time a function is called, brings up an interesting question. -What happens to local variables when the function call that created -them is no longer active? - -The following code shows an example of this. It defines a function, -`wrapValue`, which creates a local variable. It then returns a function -that accesses and returns this local variable. - -[source,javascript] ----- +Agle chapter mei hum wo tareeka dekhenge jisse function body argument ki exact list lekar usmei argument pass karayegi.yeh apke liye helpfull hoga quki isse function sare argument ko asani se accept kar leta hai isse apko confusion nahi hogi.for example:--hum isse console.log mei try karke dekhte hai-ye output hai in sabki value di hui hai. + + +Closure + +Function ko hum as a value bhi treat kar sakte hai,isse jab bhi function call kiya jayega tab tab usko new value milti rahegi.To ab socho ki jab function call hota hai to local variable ki value par kya effect hota hai socho. +Jaise niche likhe hue example mei yeh ache se samjhaya hua hai, ismei ek wrap Value nam ka function banaya hai jo ek local variable creats karta hai aur fir yeh function last mei local variable return karta hai. + function wrapValue(n) { var localVariable = n; return function() { return localVariable; }; @@ -477,557 +209,9 @@ console.log(wrap1()); // → 1 console.log(wrap2()); // → 2 ----- - -This is allowed and works as you'd hope—the variable can still be -accessed. In fact, multiple instances of the variable can be alive at -the same time, which is another good illustration of the concept that -local variables really are re-created for every call—different calls -can't trample on one another's local variables. - -This feature—being able to reference a specific instance of local -variables in an enclosing function—is called _closure_. A function -that “closes over” some local variables is called _a_ closure. This -behavior not only frees you from having to worry about lifetimes of -variables but also allows for some creative use of function values. - -(((multiplier function)))With a slight change, we can turn the -previous example into a way to create functions that multiply by an -arbitrary amount. - -[source,javascript] ----- -function multiplier(factor) { - return function(number) { - return number * factor; - }; -} - -var twice = multiplier(2); -console.log(twice(5)); -// → 10 ----- - -(((variable,from parameter)))The explicit `localVariable` from the -`wrapValue` example isn't needed since a parameter is itself a local -variable. - -(((function,model of)))Thinking about programs like this takes some -practice. A good mental model is to think of the `function` keyword as -“freezing” the code in its body and wrapping it into a package (the -function value). So when you read `return function(...) {...}`, think -of it as returning a handle to a piece of computation, frozen for -later use. - -In the example, `multiplier` returns a frozen chunk of code that gets -stored in the `twice` variable. The last line then calls the value in -this variable, causing the frozen code (`return number * factor;`) to -be activated. It still has access to the `factor` variable from the -`multiplier` call that created it, and in addition it gets access to -the argument passed when unfreezing it, 5, through its `number` -parameter. - -== Recursion == - -(((power example)))(((stack -overflow)))(((recursion)))(((function,application)))It is perfectly -okay for a function to call itself, as long as it takes care not to -overflow the stack. A function that calls itself is called -_recursive_. Recursion allows some functions to be written in a -different style. Take, for example, this alternative implementation of -`power`: - -// test: wrap - -[source,javascript] ----- -function power(base, exponent) { - if (exponent == 0) - return 1; - else - return base * power(base, exponent - 1); -} - -console.log(power(2, 3)); -// → 8 ----- - -(((loop)))(((readability)))(((mathematics)))This is rather -close to the way mathematicians define exponentiation and arguably -describes the concept in a more elegant way than the looping variant -does. The function calls itself multiple times with different -arguments to achieve the repeated multiplication. - -(((function,application)))(((efficiency)))But this implementation has -one important problem: in typical JavaScript implementations, it's -about 10 times slower than the looping version. Running through a -simple loop is a lot cheaper than calling a function multiple times. - -(((optimization)))The dilemma of speed versus ((elegance)) is an -interesting one. You can see it as a kind of continuum between -human-friendliness and machine-friendliness. Almost any program can be -made faster by making it bigger and more convoluted. The programmer -must decide on an appropriate balance. - -In the case of the link:03_functions.html#power[earlier] `power` -function, the inelegant (looping) version is still fairly simple and -easy to read. It doesn't make much sense to replace it with the -recursive version. Often, though, a program deals with such complex -concepts that giving up some efficiency in order to make the program -more straightforward becomes an attractive choice. - -(((profiling)))The basic rule, which has been repeated by many -programmers and with which I wholeheartedly agree, is to not worry -about efficiency until you know for sure that the program is too slow. -If it is, find out which parts are taking up the most time, and start -exchanging elegance for efficiency in those parts. - -Of course, this rule doesn't mean one should start ignoring -performance altogether. In many cases, like the `power` function, not -much simplicity is gained from the “elegant” approach. And sometimes -an experienced programmer can see right away that a simple approach is -never going to be fast enough. - -(((premature optimization)))The reason I'm stressing this is that -surprisingly many beginning programmers focus fanatically on -efficiency, even in the smallest details. The result is bigger, more -complicated, and often less correct programs, that take longer to -write than their more straightforward equivalents and that usually run -only marginally faster. - -(((branching recursion)))But recursion is not always just a -less-efficient alternative to looping. Some problems are much easier -to solve with recursion than with loops. Most often these are problems -that require exploring or processing several “branches”, each of which -might branch out again into more branches. - -[[recursive_puzzle]] - -(((recursion)))(((number puzzle example)))Consider this puzzle: by -starting from the number 1 and repeatedly either adding 5 or -multiplying by 3, an infinite amount of new numbers can be produced. -How would you write a function that, given a number, tries to find a -sequence of such additions and multiplications that produce that -number? For example, the number 13 could be reached by first -multiplying by 3 and then adding 5 twice, whereas the number 15 cannot -be reached at all. - -Here is a recursive solution: - -[source,javascript] ----- -function findSolution(target) { - function find(start, history) { - if (start == target) - return history; - else if (start > target) - return null; - else - return find(start + 5, "(" + history + " + 5)") || - find(start * 3, "(" + history + " * 3)"); - } - return find(1, "1"); -} - -console.log(findSolution(24)); -// → (((1 * 3) + 5) * 3) ----- - -Note that this program doesn't necessarily find the _shortest_ -sequence of operations. It is satisfied when it finds any sequence at -all. - -I don't necessarily expect you to see how it works right away. But -let's work through it, since it makes for a great exercise in -recursive thinking. - -The inner function `find` does the actual recursing. It takes two -((argument))s—the current number and a string that records how we -reached this number—and returns either a string that shows how to get -to the target or `null`. - -(((null)))(((|| operator)))(((short-circuit evaluation)))To do this, the -function performs one of three actions. If the current number is the -target number, the current history is a way to reach that target, so -it is simply returned. If the current number is greater than the -target, there's no sense in further exploring this history since both -adding and multiplying will only make the number bigger. And finally, -if we're still below the target, the function tries both possible -paths that start from the current number, by calling itself twice, -once for each of the allowed next steps. If the first call returns -something that is not `null`, it is returned. Otherwise, the second -call is returned—regardless of whether it produces a string or `null`. - -(((call stack)))To better understand how this function produces the -effect we're looking for, let's look at all the calls to `find` that -are made when searching for a solution for the number 13. - ----- -find(1, "1") - find(6, "(1 + 5)") - find(11, "((1 + 5) + 5)") - find(16, "(((1 + 5) + 5) + 5)") - too big - find(33, "(((1 + 5) + 5) * 3)") - too big - find(18, "((1 + 5) * 3)") - too big - find(3, "(1 * 3)") - find(8, "((1 * 3) + 5)") - find(13, "(((1 * 3) + 5) + 5)") - found! ----- - -The indentation suggests the depth of the call stack. The first time -`find` is called it calls itself twice to explore the solutions that start with -`(1 + 5)` and `(1 * 3)`. The first call tries to find a solution that -starts with `(1 + 5)` and, using recursion, explores _every_ solution -that yields a number less than or equal to the target number. Since -it doesn't find a solution that hits the target, it returns `null` -back to the first call. There the `||` operator causes the call that -explores `(1 * 3)` to happen. This search has more luck because its -first recursive call, through yet _another_ recursive call, hits upon -the target number, 13. This innermost recursive call returns a string, -and each of the `||` operators in the intermediate calls pass that -string along, ultimately returning our solution. - -== Growing functions == - -(((function,definition)))There are two more or less natural ways for -functions to be introduced into programs. - -(((repetition)))The first is that you find yourself writing very -similar code multiple times. We want to avoid doing that since having -more code means more space for mistakes to hide and more material to -read for people trying to understand the program. So we take the -repeated functionality, find a good name for it, and put it into a -function. - -The second way is that you find you need some functionality that you -haven't written yet and that sounds like it deserves its own function. -You'll start by naming the function, and you'll then write its body. -You might even start writing code that uses the function before you -actually define the function itself. - -(((function,naming)))(((variable,naming)))How difficult it is to find -a good name for a function is a good indication of how clear a concept -it is that you're trying to wrap. Let's go through an example. - -(((farm example)))We want to write a program that prints two numbers, -the numbers of cows and chickens on a farm, with the words `Cows` and -`Chickens` after them, and zeros padded before both numbers so that -they are always three digits long. - ----- -007 Cows -011 Chickens ----- - -That clearly asks for a function of two arguments. Let's get coding. - -[source,javascript] ----- -function printFarmInventory(cows, chickens) { - var cowString = String(cows); - while (cowString.length < 3) - cowString = "0" + cowString; - console.log(cowString + " Cows"); - var chickenString = String(chickens); - while (chickenString.length < 3) - chickenString = "0" + chickenString; - console.log(chickenString + " Chickens"); -} -printFarmInventory(7, 11); ----- - -(((length property,for string)))(((while loop)))Adding `.length` -after a string value will give us the length of that string. Thus, the -`while` loops keep adding zeros in front of the number strings until -they are at least three characters long. - -Mission accomplished! But just as we are about to send the farmer the -code (along with a hefty invoice, of course), he calls and tells us -he's also started keeping pigs, and couldn't we please extend the -software to also print pigs? - -(((copy-paste programming)))We sure can. But just as we're in the -process of copying and pasting those four lines one more time, we stop -and reconsider. There has to be a better way. Here's a first attempt: - -[source,javascript] ----- -function printZeroPaddedWithLabel(number, label) { - var numberString = String(number); - while (numberString.length < 3) - numberString = "0" + numberString; - console.log(numberString + " " + label); -} - -function printFarmInventory(cows, chickens, pigs) { - printZeroPaddedWithLabel(cows, "Cows"); - printZeroPaddedWithLabel(chickens, "Chickens"); - printZeroPaddedWithLabel(pigs, "Pigs"); -} - -printFarmInventory(7, 11, 3); ----- - -(((function,naming)))It works! But that name, -`printZeroPaddedWithLabel`, is a little awkward. It conflates three -things—printing, zero-padding, and adding a label—into a single -function. - -(((zeroPad function)))Instead of lifting out the repeated part of our -program wholesale, let's try to pick out a single _concept_. - -[source,javascript] ----- -function zeroPad(number, width) { - var string = String(number); - while (string.length < width) - string = "0" + string; - return string; -} - -function printFarmInventory(cows, chickens, pigs) { - console.log(zeroPad(cows, 3) + " Cows"); - console.log(zeroPad(chickens, 3) + " Chickens"); - console.log(zeroPad(pigs, 3) + " Pigs"); -} - -printFarmInventory(7, 16, 3); ----- - -(((readability)))(((pure function)))A function with a nice, obvious -name like `zeroPad` makes it easier for someone who reads the code to -figure out what it does. And it is useful in more situations than just -this specific program. For example, you could use it to help print -nicely aligned tables of numbers. - -(((interface,design)))How smart and versatile should our function be? -We could write anything from a terribly simple function that simply -pads a number so that it's three characters wide to a complicated -generalized number-formatting system that handles fractional numbers, -negative numbers, alignment of dots, padding with different -characters, and so on. - -A useful principle is not to add cleverness unless you are absolutely -sure you're going to need it. It can be tempting to write general -“((framework))s” for every little bit of functionality you come -across. Resist that urge. You won't get any real work done, and you'll -end up writing a lot of code that no one will ever use. - -[[pure]] -== Functions and side effects == - -(((side effect)))(((pure function)))(((function,purity)))Functions can -be roughly divided into those that are called for their side effects -and those that are called for their return value. (Though it is -definitely also possible to have both side effects and return a -value.) - -(((reuse)))The first helper function in the ((farm example)), -`printZeroPaddedWithLabel`, is called for its side effect: it prints a -line. The second version, `zeroPad`, is called for its return value. -It is no coincidence that the second is useful in more situations than -the first. Functions that create values are easier to combine in new -ways than functions that directly perform side effects. - -(((substitution)))A _pure_ function is a specific kind of -value-producing function that not only has no side effects but also -doesn't rely on side effects from other code—for example, it doesn't -read global variables that are occasionally changed by other code. A -pure function has the pleasant property that, when called with the -same arguments, it always produces the same value (and doesn't do -anything else). This makes it easy to reason about. A call to such a -function can be mentally substituted by its result, without changing -the meaning of the code. When you are not sure that a pure function is -working correctly, you can test it by simply calling it, and know that -if it works in that context, it will work in any context. Nonpure -functions might return different values based on all kinds of factors -and have side effects that might be hard to test and think about. - -(((optimization)))(((console.log)))Still, there's no need to feel bad -when writing functions that are not pure or to wage a holy war to -purge them from your code. Side effects are often useful. There'd be -no way to write a pure version of `console.log`, for example, and -`console.log` is certainly useful. Some operations are also easier to -express in an efficient way when we use side effects, so computing -speed can be a reason to avoid purity. - -== Summary == - -This chapter taught you how to write your own functions. The -`function` keyword, when used as an expression, can create a function -value. When used as a statement, it can be used to declare a variable -and give it a function as its value. - -[source,javascript] ----- -// Create a function value f -var f = function(a) { - console.log(a + 2); -}; - -// Declare g to be a function -function g(a, b) { - return a * b * 3.5; -} ----- - -A key aspect in understanding functions is understanding local scopes. -Parameters and variables declared inside a function are local to the -function, re-created every time the function is called, and not visible -from the outside. Functions declared inside another function have -access to the outer function's local scope. - -Separating the tasks your program performs into different -functions is helpful. You won't have to repeat yourself as much, and -functions can make a program more readable by grouping code into -conceptual chunks, in the same way that chapters and sections help -organize regular text. - -== Exercises == - -=== Minimum === - -(((Math object)))(((minimum (exercise))))(((Math.min -function)))(((minimum)))The -link:02_program_structure.html#return_values[previous chapter] -introduced the standard function `Math.min` that returns its smallest -argument. We can do that ourselves now. Write a function `min` that -takes two arguments and returns their minimum. - -ifdef::interactive_target[] +Jaisa apne socha tha teek vaise hi hua. Variable ke multiple example ek sath ek time par live ho sakte hai , jo ek local variable ke concept ko samjne ka ek acha examle ki local variable har call par recreate hote hai, different call se inn local variable par koi fark nhi padta. -// test: no - -[source,javascript] ----- -// Your code here. - -console.log(min(0, 10)); -// → 0 -console.log(min(0, -10)); -// → -10 ----- -endif::interactive_target[] - -!!hint!! - -(((minimum (exercise))))If you have trouble putting braces and -parentheses in the right place to get a valid function definition, -start by copying one of the examples in this chapter and modifying it. - -(((return keyword)))A function may contain multiple `return` -statements. - -!!hint!! - -=== Recursion === - -(((recursion)))(((isEven (exercise))))(((even number)))We've seen -that `%` (the remainder operator) can be used to test whether a number -is even or odd by using `% 2` to check whether it's divisible by two. -Here's another way to define whether a positive whole number is even -or odd: - -- Zero is even. - -- One is odd. - -- For any other number _N_, its evenness is the same as _N_ - 2. - -Define a recursive function `isEven` corresponding to this -description. The function should accept a `number` parameter and -return a Boolean. - -(((stack overflow)))Test it on 50 and 75. See how it behaves on -1. -Why? Can you think of a way to fix this? - -ifdef::interactive_target[] - -// test: no - -[source,javascript] ----- -// Your code here. - -console.log(isEven(50)); -// → true -console.log(isEven(75)); -// → false -console.log(isEven(-1)); -// → ?? ----- -endif::interactive_target[] - -!!hint!! - -(((isEven (exercise))))(((if keyword,chaining)))(((recursion)))Your -function will likely look somewhat similar to the inner `find` -function in the recursive `findSolution` -link:03_functions.html#recursive_puzzle[example] in this chapter, with -an `if`/`else if`/`else` chain that tests which of the three cases -applies. The final `else`, corresponding to the third case, makes the -recursive call. Each of the branches should contain a `return` -statement or in some other way arrange for a specific value to be -returned. - -(((stack overflow)))When given a negative number, the function will -recurse again and again, passing itself an ever more negative number, -thus getting further and further away from returning a result. It will -eventually run out of stack space and abort. - -!!hint!! - -=== Bean counting === - -(((bean counting (exercise))))(((charAt -method)))(((string,indexing)))(((zero-based counting)))You can get the -Nth character, or letter, from a string by writing -`"string".charAt(N)`, similar to how you get its length with -`"s".length`. The returned value will be a string containing only one -character (for example, `"b"`). The first character has position zero, -which causes the last one to be found at position `string.length - 1`. -In other words, a two-character string has length 2, and its -characters have positions 0 and 1. - -Write a function `countBs` that takes a string as its only argument -and returns a number that indicates how many uppercase “B” characters -are in the string. - -Next, write a function called `countChar` that behaves like `countBs`, -except it takes a second argument that indicates the character that is -to be counted (rather than counting only uppercase “B” characters). -Rewrite `countBs` to make use of this new function. - -ifdef::interactive_target[] - -// test: no - -[source,javascript] ----- -// Your code here. - -console.log(countBs("BBC")); -// → 2 -console.log(countChar("kakkerlak", "k")); -// → 4 ----- -endif::interactive_target[] -!!hint!! -(((bean counting (exercise))))(((length property,for -string)))(((counter variable)))A ((loop)) in your function will have -to look at every character in the string by running an index from zero -to one below its length (`< string.length`). If the character at the -current position is the same as the one the function is looking for, -it adds 1 to a counter variable. Once the loop has finished, the -counter can be returned. -(((local variable)))Take care to make all the variables used in the -function _local_ to the function by using the `var` keyword. -!!hint!! diff --git a/04_data.txt b/04_data.txt index 7de6a8ada..38bfdfeb9 100644 --- a/04_data.txt +++ b/04_data.txt @@ -1,32 +1,13 @@ -:chap_num: 4 -:prev_link: 03_functions -:next_link: 05_higher_order -:load_files: ["code/jacques_journal.js", "code/chapter/04_data.js"] -:zip: node/html - -= Data Structures: Objects and Arrays = - -[chapterquote="true"] -[quote, Charles Babbage, Passages from the Life of a Philosopher (1864)] -____ -On two occasions I have been asked, ‘Pray, -Mr. Babbage, if you put into the machine wrong figures, will the right -answers come out?’ [...] I am not able rightly to apprehend the kind -of confusion of ideas that could provoke such a question. -# -mujhe do avsaron pe pucha gaya prarthana krne kleay -Mr. Babbage, yadi aap masheen mei galat aankade daalate hain, to sahee -javaab hokar nikalate hain? [...] main is tarah kee jaanakaaree ko haasil karane mein saksham nahin hoon -aise vichaaron ke bhram kee vajah se jo is tarah ke savaal ko bhadak saken -____ +Chapter 4 +Data Structures: Objects and Arrays -(((Babbage+++,+++ Charles)))(((object)))(((data structure)))Numbers, Booleans, and strings are the +Numbers, Booleans, and strings are the bricks that ((data)) structures are built from. But you can't make much of a house out of a single brick. _Objects_ allow us to group values—including other objects—together and thus build more complex structures. # -(((Babbage+++,+++ Charles)))(((object)))(((data structure)))nambar, booliyan, aur strings hain +nambar, booliyan, aur strings hain eeton ki ((data)) dhache se bana hain lekin aap nahin bana sakte ek eent mein se adhik ek ghar _objects_ hamen group ke liye anumati deta hai or vastuon sahit objects—together aur is prakaar adhik jatil structures banaate hain From 670aa521574f74387f056b1c340e54bee52b96cf Mon Sep 17 00:00:00 2001 From: dhannukumar Date: Tue, 5 Sep 2017 04:03:57 +0530 Subject: [PATCH 05/22] 4 chapter --- 04_data.txt | 44 +++++++++++++++++--------------------------- 1 file changed, 17 insertions(+), 27 deletions(-) diff --git a/04_data.txt b/04_data.txt index 7de6a8ada..6bad05482 100644 --- a/04_data.txt +++ b/04_data.txt @@ -1,23 +1,17 @@ :chap_num: 4 -:prev_link: 03_functions -:next_link: 05_higher_order -:load_files: ["code/jacques_journal.js", "code/chapter/04_data.js"] -:zip: node/html - = Data Structures: Objects and Arrays = -[chapterquote="true"] -[quote, Charles Babbage, Passages from the Life of a Philosopher (1864)] -____ + On two occasions I have been asked, ‘Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out?’ [...] I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question. -# -mujhe do avsaron pe pucha gaya prarthana krne kleay + +#hindi# +mujh se do avsaron pe pucha gaya pray karne ke liye Mr. Babbage, yadi aap masheen mei galat aankade daalate hain, to sahee -javaab hokar nikalate hain? [...] main is tarah kee jaanakaaree ko haasil karane mein saksham nahin hoon -aise vichaaron ke bhram kee vajah se jo is tarah ke savaal ko bhadak saken +javaab hokar nikalate hain? [...] main iss tarah ki jaanakari ko hasil karne mein saksham nahin hoon +Bhadkane wale saval se vicharon ka bhram ho sakta hain. ____ (((Babbage+++,+++ Charles)))(((object)))(((data structure)))Numbers, Booleans, and strings are the @@ -25,32 +19,28 @@ bricks that ((data)) structures are built from. But you can't make much of a house out of a single brick. _Objects_ allow us to group values—including other objects—together and thus build more complex structures. -# -(((Babbage+++,+++ Charles)))(((object)))(((data structure)))nambar, booliyan, aur strings hain -eeton ki ((data)) dhache se bana hain lekin aap nahin bana sakte -ek eent mein se adhik ek ghar _objects_ hamen group ke liye anumati deta hai -or vastuon sahit objects—together aur is prakaar adhik jatil structures banaate hain + +#hindi# +(((Babbage+++,+++ Charles)))(((object)))(((data structure)))Number, Booleans, aur strings yah sab +bricks ((data)) hote hain. Lekin ham single bricks se house nahi bana sakta hain par _Objects_group values allow +karta hain aur object ke sath ham jyada complex structures bana sakte hain. The programs we have built so far have been seriously hampered by the fact that they were operating only on simple data types. This chapter will add a basic understanding of data structures to your toolkit. By the end of it, you'll know enough to start writing some useful programs. -# -ab tak hamane jo programs banae hain, use gambheerata se baadhit kiya gaya hai -fact yah hai ki ve keval saral data types par kaam kar rahe the. yah chapter -aapake basic mein data structures kee toolkit samajh ke jod dega. dvaara -isake last mein, aap kuchh upayogee likhana shuroo karane ke lie useful programs jaanate honge + +#hindi# +Ab tak hamne jo program banaye hain, usse baadhit kiya gaya hai +fact yah hai ki keval simple data types par kaam kar rahe the. yah chapter +aapake basic data structures ko samjhne me madad karenga. iske last mei app itne able ho jayenge ki app +ek useful program start kar sakte hain. The chapter will work through a more or less realistic programming example, introducing concepts as they apply to the problem at hand. The example code will often build on functions and variables that were introduced earlier in the text. -# -Chapter adhik ya kam prograaming ke maadhyam se kaam karega -example ke liye, introducing ko present karana kyonki ve samasya par haath mein lage hote hain. -Jo example hain wo code function aur veriebal build karta hain par banaayega jo ki the -pahale paath mein introduced kiya hain. ifdef::book_target[] From 1e2aeeb41222130e64d17c945313d8671c063858 Mon Sep 17 00:00:00 2001 From: shivam8800 Date: Tue, 5 Sep 2017 04:07:14 +0530 Subject: [PATCH 06/22] changese some pharagrapes in chapter -5 --- 05_higher_order.txt | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/05_higher_order.txt b/05_higher_order.txt index e29c4c402..eba23319a 100644 --- a/05_higher_order.txt +++ b/05_higher_order.txt @@ -9,7 +9,6 @@ programmers, in turn, tend to introduce mistakes (_((bug))s_) into programs. A large program also provides a lot of space for these bugs to hide, making them hard to find. - ///** HINDI **// (((prograam aakaar))) ek bada kaaryakram mahanga kaaryakram @@ -26,6 +25,10 @@ rahee hai programs in the introduction. The first is self-contained and six lines long. +//**HINDI**// +Hum ab 2 example lenge jo humne Introduction chapter mei pade the. +To pehla example six lines lamba aur self contained hai. + [source,javascript] ---- var total = 0, count = 1; @@ -38,27 +41,38 @@ console.log(total); The second relies on two external functions and is one line long. +//**HINDI**// +Aur seccond 2 bahari function par depend karta hhai aur wo 1 line ka hai. + + [source,javascript] ---- console.log(sum(range(1, 10))); ---- Which one is more likely to contain a bug? - -(((program size)))If we count the size of the definitions of `sum` and +If we count the size of the definitions of `sum` and `range`, the second program is also big—even bigger than the first. But still, I'd argue that it is more likely to be correct. - -(((abstraction)))(((domain-specific language)))It is more likely to -be correct because the solution is expressed in a ((vocabulary)) that +It is more likely to be correct because the solution is expressed in a ((vocabulary)) that corresponds to the problem being solved. Summing a range of numbers isn't about loops and counters. It is about ranges and sums. + The definitions of this vocabulary (the functions `sum` and `range`) will still involve loops, counters, and other incidental details. But because they are expressing simpler concepts than the program as a whole, they are easier to get right. + +//**HINDI**// +Upper wale dono examples mei se kismei bug hai mtlb todi bahut galti hai? +Agar hum 'sum' aur 'range' ki defination ka size count kare to, Second program bada hai first se.lekin hum abhi bhi second example ko correct kahenge.kyuki uska solution problem solve krne se related karta hai aur kam code bhi hai. +Numbers ki range loops aur counters par depend ni karti wo keval ranges and sums par depend karti hai. + +'sum' aur 'range' ki definitions mei abhi bhi loops aur counters available hai.kyuki isse hume pure program ka flow pta chlta hai aur isse kisi bhi concept ko aaram se smjh sakte hai. + + == Abstraction == In the context of programming, these kinds of vocabularies are usually From d16f3464f5af3b0e3fd4d67b985c8de0da0443f7 Mon Sep 17 00:00:00 2001 From: dhannukumar Date: Tue, 5 Sep 2017 04:31:40 +0530 Subject: [PATCH 07/22] review ch 5 --- 05_higher_order.txt | 32 +++++++++----------------------- 1 file changed, 9 insertions(+), 23 deletions(-) diff --git a/05_higher_order.txt b/05_higher_order.txt index eba23319a..59c8ca097 100644 --- a/05_higher_order.txt +++ b/05_higher_order.txt @@ -9,7 +9,8 @@ programmers, in turn, tend to introduce mistakes (_((bug))s_) into programs. A large program also provides a lot of space for these bugs to hide, making them hard to find. -///** HINDI **// + +///** HINDI **// (((prograam aakaar))) ek bada kaaryakram mahanga kaaryakram hai, na ki bas kyonki us samay ke nirmaan ke lie leta hai aakaar lagabhag @@ -25,10 +26,6 @@ rahee hai programs in the introduction. The first is self-contained and six lines long. -//**HINDI**// -Hum ab 2 example lenge jo humne Introduction chapter mei pade the. -To pehla example six lines lamba aur self contained hai. - [source,javascript] ---- var total = 0, count = 1; @@ -41,38 +38,27 @@ console.log(total); The second relies on two external functions and is one line long. -//**HINDI**// -Aur seccond 2 bahari function par depend karta hhai aur wo 1 line ka hai. - - [source,javascript] ---- console.log(sum(range(1, 10))); ---- Which one is more likely to contain a bug? -If we count the size of the definitions of `sum` and + +(((program size)))If we count the size of the definitions of `sum` and `range`, the second program is also big—even bigger than the first. But still, I'd argue that it is more likely to be correct. -It is more likely to be correct because the solution is expressed in a ((vocabulary)) that + +(((abstraction)))(((domain-specific language)))It is more likely to +be correct because the solution is expressed in a ((vocabulary)) that corresponds to the problem being solved. Summing a range of numbers isn't about loops and counters. It is about ranges and sums. - The definitions of this vocabulary (the functions `sum` and `range`) will still involve loops, counters, and other incidental details. But because they are expressing simpler concepts than the program as a whole, they are easier to get right. - -//**HINDI**// -Upper wale dono examples mei se kismei bug hai mtlb todi bahut galti hai? -Agar hum 'sum' aur 'range' ki defination ka size count kare to, Second program bada hai first se.lekin hum abhi bhi second example ko correct kahenge.kyuki uska solution problem solve krne se related karta hai aur kam code bhi hai. -Numbers ki range loops aur counters par depend ni karti wo keval ranges and sums par depend karti hai. - -'sum' aur 'range' ki definitions mei abhi bhi loops aur counters available hai.kyuki isse hume pure program ka flow pta chlta hai aur isse kisi bhi concept ko aaram se smjh sakte hai. - - == Abstraction == In the context of programming, these kinds of vocabularies are usually @@ -408,7 +394,7 @@ data storage and communication format on the Web. (((array)))(((object)))(((quoting,in JSON)))(((comment)))JSON is similar to JavaScript's way of writing arrays and objects, with a few restrictions. All property names have to be surrounded by double quotes, and -only simple data expressions are allowed—no function calls, +only simple data expressions are allowed—no function calls, variables, or anything that involves actual computation. Comments are not allowed in JSON. @@ -1052,7 +1038,7 @@ that maps group names to arrays of group members. method)))(((some method)))(((array,methods)))(((&& operator)))(((|| operator)))Arrays also come with the standard methods `every` and `some`. Both take a predicate function that, when called with an array -element as argument, returns true or false. Just like `&&` +element as argument, returns true or false. Just like `&&` returns a true value only when the expressions on both sides are true, `every` returns true only when the predicate returns true for _all_ elements of the array. Similarly, `some` returns true as soon as the From 12f5a531f874906c5b50a4059ef40bd273896be4 Mon Sep 17 00:00:00 2001 From: dhannukumar Date: Tue, 5 Sep 2017 04:36:20 +0530 Subject: [PATCH 08/22] recieving 5th file --- 05_higher_order.txt | 1084 ------------------------------------------- 1 file changed, 1084 deletions(-) delete mode 100644 05_higher_order.txt diff --git a/05_higher_order.txt b/05_higher_order.txt deleted file mode 100644 index 59c8ca097..000000000 --- a/05_higher_order.txt +++ /dev/null @@ -1,1084 +0,0 @@ -Chapter 5 -Higher-Order Functions[quote, Master Yuan-Ma, The Book of Programming] -____ - -(((program size)))A large program is a costly program, and not just -because of the time it takes to build. Size almost always involves -((complexity)), and complexity confuses programmers. Confused -programmers, in turn, tend to introduce mistakes (_((bug))s_) into -programs. A large program also provides a lot of space for these bugs -to hide, making them hard to find. - - -///** HINDI **// - -(((prograam aakaar))) ek bada kaaryakram mahanga kaaryakram -hai, na ki bas kyonki us samay ke nirmaan ke lie leta hai aakaar lagabhag -hamesha shaamil hota hai (jatilata)), aur jatilata prograamar ko bhramit -karatee hai pareshaan prograamar, badale mein, galatiyon ko shuroo karate hain -(_ ((bag)) s_) mein kaaryakram. ek bada kaaryakram in bagon ke lie bahut saare -sthaan pradaan karata hai chhupaane ke lie, unhen khojane ke lie mushkil bana -rahee hai - - - -(((summing example)))Let's briefly go back to the final two example -programs in the introduction. The first is self-contained and six -lines long. - -[source,javascript] ----- -var total = 0, count = 1; -while (count <= 10) { - total += count; - count += 1; -} -console.log(total); ----- - -The second relies on two external functions and is one line long. - -[source,javascript] ----- -console.log(sum(range(1, 10))); ----- - -Which one is more likely to contain a bug? - -(((program size)))If we count the size of the definitions of `sum` and -`range`, the second program is also big—even bigger than the first. -But still, I'd argue that it is more likely to be correct. - -(((abstraction)))(((domain-specific language)))It is more likely to -be correct because the solution is expressed in a ((vocabulary)) that -corresponds to the problem being solved. Summing a range of -numbers isn't about loops and counters. It is about ranges and sums. - -The definitions of this vocabulary (the functions `sum` and `range`) -will still involve loops, counters, and other incidental details. But -because they are expressing simpler concepts than the program as a -whole, they are easier to get right. - -== Abstraction == - -In the context of programming, these kinds of vocabularies are usually -called _((abstraction))s_. Abstractions hide details and give us the -ability to talk about problems at a higher (or more abstract) level. - -(((recipe analogy)))(((pea soup)))As an analogy, compare these two -recipes for pea soup: - -____ -Put 1 cup of dried peas per person into a container. Add water until -the peas are well covered. Leave the peas in water for at least 12 hours. -Take the peas out of the water and put them in a cooking pan. Add 4 -cups of water per person. Cover the pan and keep the peas -simmering for two hours. Take half an onion per person. Cut it into -pieces with a knife. Add it to the peas. Take a stalk of celery per -person. Cut it into pieces with a knife. Add it to the peas. Take a -carrot per person. Cut it into pieces. With a knife! Add it to the -peas. Cook for 10 more minutes. -____ - -And the second recipe: -____ -Per person: 1 cup dried split peas, half a chopped onion, a stalk of -celery, and a carrot. - -Soak peas for 12 hours. Simmer for 2 hours in 4 cups of water -(per person). Chop and add vegetables. Cook for 10 more minutes. -____ - -(((vocabulary)))The second is shorter and easier to interpret. But -you do need to understand a few more cooking-related words—__soak__, -_simmer_, _chop_, and, I guess, _vegetable_. - -When programming, we can't rely on all the words we need to be waiting -for us in the dictionary. Thus, you might fall into the pattern of the -first recipe—work out the precise steps the computer has to perform, -one by one, blind to the higher-level concepts that they express. - -(((abstraction)))It has to become second nature, for a programmer, to -notice when a concept is begging to be abstracted into a new word. - -== Abstracting array traversal == - -(((array)))Plain functions, as we've seen them so far, are a good -way to build abstractions. But sometimes they fall short. - -(((for loop)))In the link:04_data.html#data[previous chapter], this -type of `for` ((loop)) made several appearances: - -[source,javascript] ----- -var array = [1, 2, 3]; -for (var i = 0; i < array.length; i++) { - var current = array[i]; - console.log(current); -} ----- - -(((length property,for -array)))(((array,indexing)))(((readability)))It's trying to say, “For -each element in the array, log it to the console”. But it uses a -roundabout way that involves a counter variable `i`, a check against -the array's length, and an extra variable declaration to pick out the -current element. Apart from being a bit of an eyesore, this provides a -lot of space for potential mistakes. We might accidentally reuse the -`i` variable, misspell `length` as `lenght`, confuse the `i` and `current` -variables, and so on. - -So let's try to abstract this into a function. Can you think of a way? - -Well, it's easy to write a function that goes over an array and calls -`console.log` on every element. - -[source,javascript] ----- -function logEach(array) { - for (var i = 0; i < array.length; i++) - console.log(array[i]); -} ----- - -[[forEach]] -indexsee:[higher-order function,function+++,+++ higher-order](((function,higher-order)))(((loop)))(((array,traversal)))(((function,as value)))(((forEach method)))But what -if we want to do something other than logging the elements? Since -“doing something” can be represented as a function and functions are -just values, we can pass our action as a function value. - -[source,javascript] ----- -function forEach(array, action) { - for (var i = 0; i < array.length; i++) - action(array[i]); -} - -forEach(["Wampeter", "Foma", "Granfalloon"], console.log); -// → Wampeter -// → Foma -// → Granfalloon ----- - -(In some browsers, calling `console.log` in this way does not work. -You can use `alert` instead of `console.log` if this example fails to -work.) - -Often, you don't pass a predefined function to `forEach` but create -a function value on the spot instead. - -[source,javascript] ----- -var numbers = [1, 2, 3, 4, 5], sum = 0; -forEach(numbers, function(number) { - sum += number; -}); -console.log(sum); -// → 15 ----- - -(((loop body)))(((curly braces)))This looks quite a lot like the -classical `for` loop, with its body written as a block below it. -However, now the body is inside the function value, as well as -inside the ((parentheses)) of the call to `forEach`. This is why it -has to be closed with the closing brace _and_ closing parenthesis. - -(((local variable)))(((parameter)))Using this pattern, we can -specify a variable name for the current element (`number`), rather -than having to pick it out of the array manually. - -(((array,methods)))(((function,higher-order)))(((forEach -method)))(((array)))In fact, we don't need to write `forEach` -ourselves. It is available as a standard method on arrays. Since the -array is already provided as the thing the method acts on, `forEach` -takes only one required argument: the function to be executed for each -element. - -To illustrate how helpful this is, let's look back at a function -from link:04_data.html#analysis[the previous chapter]. It contains two -array-traversing ((loop))s. - -[source,javascript] ----- -function gatherCorrelations(journal) { - var phis = {}; - for (var entry = 0; entry < journal.length; entry++) { - var events = journal[entry].events; - for (var i = 0; i < events.length; i++) { - var event = events[i]; - if (!(event in phis)) - phis[event] = phi(tableFor(event, journal)); - } - } - return phis; -} ----- - -(((forEach method)))Working with `forEach` makes it slightly shorter -and quite a bit cleaner. - -[source,javascript] ----- -function gatherCorrelations(journal) { - var phis = {}; - journal.forEach(function(entry) { - entry.events.forEach(function(event) { - if (!(event in phis)) - phis[event] = phi(tableFor(event, journal)); - }); - }); - return phis; -} ----- - -== Higher-order functions == - -(((function,higher-order)))(((function,as value)))Functions that -operate on other functions, either by taking them as arguments or by -returning them, are called _higher-order functions_. If you have -already accepted the fact that functions are regular values, there is -nothing particularly remarkable about the fact that such functions -exist. The term comes from ((mathematics)), where the distinction -between functions and other values is taken more seriously. - -(((abstraction)))Higher-order functions allow us to abstract over -_actions_, not just values. They come in several forms. For example, -you can have functions that create new functions. - -[source,javascript] ----- -function greaterThan(n) { - return function(m) { return m > n; }; -} -var greaterThan10 = greaterThan(10); -console.log(greaterThan10(11)); -// → true ----- - -And you can have functions that change other functions. - -[source,javascript] ----- -function noisy(f) { - return function(arg) { - console.log("calling with", arg); - var val = f(arg); - console.log("called with", arg, "- got", val); - return val; - }; -} -noisy(Boolean)(0); -// → calling with 0 -// → called with 0 - got false ----- - -You can even write functions that provide new types of ((control flow)). - -[source,javascript] ----- -function unless(test, then) { - if (!test) then(); -} -function repeat(times, body) { - for (var i = 0; i < times; i++) body(i); -} - -repeat(3, function(n) { - unless(n % 2, function() { - console.log(n, "is even"); - }); -}); -// → 0 is even -// → 2 is even ----- - -(((inner function)))(((nesting,of functions)))((({} -(block))))(((local variable)))(((closure)))The ((lexical scoping)) -rules that we discussed in link:03_functions.html#scoping[Chapter 3] -work to our advantage when using functions in this way. In the previous example, the `n` variable is a ((parameter)) to the outer function. -Because the inner function lives inside the environment of the outer -one, it can use `n`. The bodies of such inner functions can access the -variables around them. They can play a role similar to the `{}` blocks -used in regular loops and conditional statements. An important -difference is that variables declared inside inner functions do not -end up in the environment of the outer function. And that is usually a -good thing. - -== Passing along arguments == - -(((function,wrapping)))(((arguments object)))The `noisy` function -defined earlier, which wraps its argument in another function, has a rather -serious deficit. - -[source,javascript] ----- -function noisy(f) { - return function(arg) { - console.log("calling with", arg); - var val = f(arg); - console.log("called with", arg, "- got", val); - return val; - }; -} ----- - -If `f` takes more than one ((parameter)), it gets only the first one. -We could add a bunch of arguments to the inner function (`arg1`, -`arg2`, and so on) and pass them all to `f`, but it is not clear how many -would be enough. This solution would also deprive `f` of the -information in `arguments.length`. Since we'd always pass the same -number of arguments, it wouldn't know how many arguments were -originally given. - -(((apply method)))(((array-like object)))(((function,application)))For -these kinds of situations, JavaScript functions have an `apply` -method. You pass it an array (or array-like object) of arguments, and -it will call the function with those arguments. - -[source,javascript] ----- -function transparentWrapping(f) { - return function() { - return f.apply(null, arguments); - }; -} ----- - -(((null)))That's a useless function, but it shows the pattern we are -interested in—the function it returns passes all of the given -arguments, and only those arguments, to `f`. It does this by passing -its own `arguments` object to `apply`. The first argument to `apply`, -for which we are passing `null` here, can be used to simulate a -((method)) call. We will come back to that in the -link:06_object.html#call_method[next chapter]. - -== JSON == - -(((array)))(((function,higher-order)))(((forEach method)))(((data -set)))Higher-order functions that somehow apply a function to the -elements of an array are widely used in JavaScript. The `forEach` -method is the most primitive such function. There are a number of -other variants available as methods on arrays. To familiarize -ourselves with them, let's play around with another data set. - -(((ancestry example)))A few years ago, someone crawled through a lot -of archives and put together a book on the history of my family name -(Haverbeke—meaning Oatbrook). I opened it hoping to find -knights, pirates, and alchemists ... but the book turns out to be -mostly full of Flemish ((farmer))s. For my amusement, I extracted the -information on my direct ancestors and put it into a -computer-readable format. - -(((data format)))(((JSON)))The file I created looks something like -this: - -[source,application/json] ----- -[ - {"name": "Emma de Milliano", "sex": "f", - "born": 1876, "died": 1956, - "father": "Petrus de Milliano", - "mother": "Sophia van Damme"}, - {"name": "Carolus Haverbeke", "sex": "m", - "born": 1832, "died": 1905, - "father": "Carel Haverbeke", - "mother": "Maria van Brussel"}, - … and so on -] ----- - -indexsee:[JavaScript Object Notation,JSON](((World Wide Web)))This format is called JSON (pronounced “Jason”), -which stands for JavaScript Object Notation. It is widely used as a -data storage and communication format on the Web. - -(((array)))(((object)))(((quoting,in JSON)))(((comment)))JSON is similar to -JavaScript's way of writing arrays and objects, with a few -restrictions. All property names have to be surrounded by double quotes, and -only simple data expressions are allowed—no function calls, -variables, or anything that involves actual computation. Comments are not -allowed in JSON. - -(((JSON.stringify function)))(((JSON.parse -function)))(((serialization)))(((deserialization)))(((parsing)))JavaScript -gives us functions, `JSON.stringify` and `JSON.parse`, that convert -data to and from this format. The first takes a JavaScript value and -returns a JSON-encoded string. The second takes such a string and -converts it to the value it encodes. - -[source,javascript] ----- -var string = JSON.stringify({name: "X", born: 1980}); -console.log(string); -// → {"name":"X","born":1980} -console.log(JSON.parse(string).born); -// → 1980 ----- - -(((ANCESTRY_FILE data set)))The variable `ANCESTRY_FILE`, available in -the ((sandbox)) for this chapter and in -http://eloquentjavascript.net/code/ancestry.js[a downloadable file] on -the website(!book (http://eloquentjavascript.net/code#5[_eloquentjavascript.net/code#5_])!), contains the -content of my ((JSON)) file as a string. Let's decode it and see how -many people it contains. - -// include_code strip_log - -[source,javascript] ----- -var ancestry = JSON.parse(ANCESTRY_FILE); -console.log(ancestry.length); -// → 39 ----- - -== Filtering an array == - -(((array,methods)))(((array,filtering)))(((filter -method)))(((function,higher-order)))(((predicate function)))To find -the people in the ancestry data set who were young in 1924, the -following function might be helpful. It filters out the elements in an -array that don't pass a test. - -[source,javascript] ----- -function filter(array, test) { - var passed = []; - for (var i = 0; i < array.length; i++) { - if (test(array[i])) - passed.push(array[i]); - } - return passed; -} - -console.log(filter(ancestry, function(person) { - return person.born > 1900 && person.born < 1925; -})); -// → [{name: "Philibert Haverbeke", …}, …] ----- - -(((function,as value)))(((function,application)))This uses the -argument named `test`, a function value, to fill in a “gap” in the -computation. The `test` function is called for each element, and its -return value determines whether an element is included in the returned -array. - -(((ancestry example)))Three people in the file were alive and young in -1924: my grandfather, grandmother, and great-aunt. - -(((filter method)))(((pure function)))(((side effect)))Note how the -`filter` function, rather than deleting elements from the existing -array, builds up a new array with only the elements that pass the -test. This function is _pure_. It does not modify the array it is -given. - -Like `forEach`, `filter` is also a ((standard)) method on arrays. The -example defined the function only in order to show what it does -internally. From now on, we'll use it like this instead: - -[source,javascript] ----- -console.log(ancestry.filter(function(person) { - return person.father == "Carel Haverbeke"; -})); -// → [{name: "Carolus Haverbeke", …}] ----- - -== Transforming with map == - -(((array,methods)))(((map method)))(((ancestry example)))Say we -have an array of objects representing people, produced by filtering -the `ancestry` array somehow. But we want an array of names, which is -easier to read. - -(((function,higher-order)))The `map` method transforms an array by -applying a function to all of its elements and building a new array -from the returned values. The new array will have the same length as -the input array, but its content will have been “mapped” to a new form -by the function. - -// test: join - -[source,javascript] ----- -function map(array, transform) { - var mapped = []; - for (var i = 0; i < array.length; i++) - mapped.push(transform(array[i])); - return mapped; -} - -var overNinety = ancestry.filter(function(person) { - return person.died - person.born > 90; -}); -console.log(map(overNinety, function(person) { - return person.name; -})); -// → ["Clara Aernoudts", "Emile Haverbeke", -// "Maria Haverbeke"] ----- - -Interestingly, the people who lived to at least 90 years of age are the -same three people who we saw before—the people who were young in the -1920s, which happens to be the most recent generation in my data set. -I guess ((medicine)) has come a long way. - -Like `forEach` and `filter`, `map` is also a standard method on -arrays. - -== Summarizing with reduce == - -(((array,methods)))(((summing example)))(((reduce method)))(((ancestry -example)))Another common pattern of computation on arrays is computing -a single value from them. Our recurring example, summing a collection -of numbers, is an instance of this. Another example would be finding -the person with the earliest year of birth in the data set. - -(((function,higher-order)))(((fold function)))The higher-order -operation that represents this pattern is called _reduce_ (or -sometimes _fold_). You can think of it as folding up the array, one -element at a time. When summing numbers, you'd start with the number -zero and, for each element, combine it with the current sum by adding -the two. - -The parameters to the `reduce` function are, apart from the array, a -combining function and a start value. This function is a little less -straightforward than `filter` and `map`, so pay close attention. - -[source,javascript] ----- -function reduce(array, combine, start) { - var current = start; - for (var i = 0; i < array.length; i++) - current = combine(current, array[i]); - return current; -} - -console.log(reduce([1, 2, 3, 4], function(a, b) { - return a + b; -}, 0)); -// → 10 ----- - -(((reduce method)))The standard array method `reduce`, which of course -corresponds to this function, has an added convenience. If your array -contains at least one element, you are allowed to leave off the -`start` argument. The method will take the first element of the array -as its start value and start reducing at the second element. - -(((ancestry example)))(((minimum)))To use `reduce` to find my most -ancient known ancestor, we can write something like this: - -// test: no - -[source,javascript] ----- -console.log(ancestry.reduce(function(min, cur) { - if (cur.born < min.born) return cur; - else return min; -})); -// → {name: "Pauwels van Haverbeke", born: 1535, …} ----- - -== Composability == - -(((loop)))(((minimum)))(((ancestry example)))Consider how we would -have written the previous example (finding the person with the -earliest year of birth) without higher-order functions. The code is -not that much worse. - -// test: no - -[source,javascript] ----- -var min = ancestry[0]; -for (var i = 1; i < ancestry.length; i++) { - var cur = ancestry[i]; - if (cur.born < min.born) - min = cur; -} -console.log(min); -// → {name: "Pauwels van Haverbeke", born: 1535, …} ----- - -There are a few more ((variable))s, and the program is two lines -longer but still quite easy to understand. - -[[average_function]] -(((average -function)))(((composability)))(((function,higher-order)))Higher-order -functions start to shine when you need to _compose_ functions. As an -example, let's write code that finds the average age for men and for -women in the data set. - -// test: clip - -[source,javascript] ----- -function average(array) { - function plus(a, b) { return a + b; } - return array.reduce(plus) / array.length; -} -function age(p) { return p.died - p.born; } -function male(p) { return p.sex == "m"; } -function female(p) { return p.sex == "f"; } - -console.log(average(ancestry.filter(male).map(age))); -// → 61.67 -console.log(average(ancestry.filter(female).map(age))); -// → 54.56 ----- - -(((plus function)))(((+ operator)))(((function,as value)))(It's a bit -silly that we have to define `plus` as a function, but operators in -JavaScript, unlike functions, are not values, so you can't pass them -as arguments.) - -(((abstraction)))(((vocabulary)))Instead of tangling the logic into a -big ((loop)), it is neatly composed into the concepts we are -interested in—determining sex, computing age, and averaging numbers. We -can apply these one by one to get the result we are looking for. - -This is _fabulous_ for writing clear code. Unfortunately, this clarity -comes at a cost. - -== The cost == - -(((efficiency)))(((optimization)))In the happy land of elegant code -and pretty rainbows, there lives a spoil-sport monster called -_inefficiency_. - -(((elegance)))(((array,creation)))(((pure -function)))(((composability)))A program that processes an array is most -elegantly expressed as a sequence of cleanly separated steps that each -do something with the array and produce a new array. But building up -all those intermediate arrays is somewhat expensive. - -(((readability)))(((function,application)))(((forEach -method)))(((function,as value)))Likewise, passing a function to -`forEach` and letting that method handle the array iteration for us is -convenient and easy to read. But function calls in JavaScript are -costly compared to simple loop bodies. - -(((abstraction)))And so it goes with a lot of techniques that help -improve the clarity of a program. Abstractions add layers between the -raw things the computer is doing and the concepts we are working with -and thus cause the machine to perform more work. This is not an iron -law—there are programming languages that have better support for -building abstractions without adding inefficiencies, and even in -JavaScript, an experienced programmer can find ways to write abstract -code that is still fast. But it is a problem that comes up a lot. - -(((profiling)))Fortunately, most computers are insanely fast. If you -are processing a modest set of data or doing something that has -to happen only on a human time scale (say, every time the user clicks a -button), then it _does not matter_ whether you wrote a pretty solution -that takes half a millisecond or a super-optimized solution that takes -a tenth of a millisecond. - -(((nesting,of loops)))(((inner loop)))(((complexity)))It is helpful to -roughly keep track of how often a piece of your program is going to -run. If you have a ((loop)) inside a loop (either directly or through -the outer loop calling a function that ends up performing the inner -loop), the code inside the inner loop will end up running __N__×__M__ -times, where _N_ is the number of times the outer loop repeats and -_M_ is the number of times the inner loop repeats within each iteration -of the outer loop. If that inner loop contains another loop that makes -_P_ rounds, its body will run __M__×__N__×__P__ times, and so on. This -can add up to large numbers, and when a program is slow, the problem -can often be traced to only a small part of the code, which sits inside an inner loop. - -== Great-great-great-great-... == - -(((ancestry example)))My ((grandfather)), Philibert Haverbeke, is -included in the data file. By starting with him, I can trace my -lineage to find out whether the most ancient person in the data, -Pauwels van Haverbeke, is my direct ancestor. And if he is, I would -like to know how much ((DNA)) I theoretically share with him. - -(((byName object)))(((map)))(((data structure)))(((object,as -map)))To be able to go from a parent's name to the actual object that -represents this person, we first build up an object that associates -names with people. - -// include_code strip_log - -[source,javascript] ----- -var byName = {}; -ancestry.forEach(function(person) { - byName[person.name] = person; -}); - -console.log(byName["Philibert Haverbeke"]); -// → {name: "Philibert Haverbeke", …} ----- - -Now, the problem is not entirely as simple as following the `father` -properties and counting how many we need to reach Pauwels. There are -several cases in the family ((tree)) where people married their second -cousins (tiny villages and all that). This causes the branches of the -family tree to rejoin in a few places, which means I share more than -1/2^_G_^ of my genes with this person, where _G_ for the number of -generations between Pauwels and me. This formula comes from the idea -that each generation splits the gene pool in two. - -(((reduce method)))(((data structure)))A reasonable way to think about -this problem is to look at it as being analogous to `reduce`, which -condenses an array to a single value by repeatedly combining -values, left to right. In this case, we also want to condense our data -structure to a single value but in a way that follows family -lines. The _shape_ of the data is that of a family tree, rather than a -flat list. - -The way we want to reduce this shape is by computing a value for a -given person by combining values from their ancestors. This can be -done recursively: if we are interested in person _A_, we have to -compute the values for __A__’s parents, which in turn requires us to -compute the value for __A__’s grandparents, and so on. In principle, -that'd require us to look at an infinite number of people, but since -our data set is finite, we have to stop somewhere. We'll allow a -((default value)) to be given to our reduction function, which will be -used for people who are not in the data. In our case, that value is -simply zero, on the assumption that people not in the list don't share -DNA with the ancestor we are looking at. - -(((recursion)))(((reduceAncestors function)))Given a person, a -function to combine values from the two parents of a given person, and -a default value, `reduceAncestors` condenses a value from a family -tree. - -// include_code - -[source,javascript] ----- -function reduceAncestors(person, f, defaultValue) { - function valueFor(person) { - if (person == null) - return defaultValue; - else - return f(person, valueFor(byName[person.mother]), - valueFor(byName[person.father])); - } - return valueFor(person); -} ----- - -(((function,higher-order)))The inner function (`valueFor`) handles a -single person. Through the ((magic)) of recursion, it can simply call -itself to handle the father and the mother of this person. The -results, along with the person object itself, are passed to `f`, which -returns the actual value for this person. - -We can then use this to compute the amount of ((DNA)) my -((grandfather)) shared with Pauwels van Haverbeke and divide that by -four. - -// start_code bottom_lines: 2 -// test: clip -// include_code top_lines: 6 - -[source,javascript] ----- -function sharedDNA(person, fromMother, fromFather) { - if (person.name == "Pauwels van Haverbeke") - return 1; - else - return (fromMother + fromFather) / 2; -} -var ph = byName["Philibert Haverbeke"]; -console.log(reduceAncestors(ph, sharedDNA, 0) / 4); -// → 0.00049 ----- - -The person with the name Pauwels van Haverbeke obviously shared 100 percent -of his DNA with Pauwels van Haverbeke (there are no people who share -names in the data set), so the function returns 1 for him. All other -people share the average of the amounts that their parents share. - -So, statistically speaking, I share about 0.05 percent of my ((DNA)) with -this 16th-century person. It should be noted that this is only a -statistical approximation, not an exact amount. It is a rather small -number, but given how much genetic material we carry (about 3 billion -base pairs), there's still probably some aspect in the biological -machine that is me that originates with Pauwels. - -(((ancestry example)))(((reduceAncestors -function)))(((abstraction)))We could also have computed this number -without relying on `reduceAncestors`. But separating the general -approach (condensing a family tree) from the specific case (computing -shared DNA) can improve the clarity of the code and allows us to reuse -the abstract part of the program for other cases. For example, the -following code finds the percentage of a person's known ancestors who -lived past 70 (by lineage, so people may be counted multiple times): - -// test: clip - -[source,javascript] ----- -function countAncestors(person, test) { - function combine(current, fromMother, fromFather) { - var thisOneCounts = current != person && test(current); - return fromMother + fromFather + (thisOneCounts ? 1 : 0); - } - return reduceAncestors(person, combine, 0); -} -function longLivingPercentage(person) { - var all = countAncestors(person, function(person) { - return true; - }); - var longLiving = countAncestors(person, function(person) { - return (person.died - person.born) >= 70; - }); - return longLiving / all; -} -console.log(longLivingPercentage(byName["Emile Haverbeke"])); -// → 0.129 ----- - -Such numbers are not to be taken too seriously, given that -our data set contains a rather arbitrary collection of people. But the -code illustrates the fact that `reduceAncestors` gives us a useful -piece of ((vocabulary)) for working with the family tree data -structure. - -== Binding == - -(((bind method)))(((partial -application)))(((function,application)))The `bind` method, which all -functions have, creates a new function that will call the original -function but with some of the arguments already fixed. - -(((filter method)))(((function,as value)))The following code shows an -example of `bind` in use. It defines a function `isInSet` that -tells us whether a person is in a given set of strings. To call -`filter` in order to collect those person objects whose names are in a -specific set, we can either write a function expression that makes a -call to `isInSet` with our set as its first argument or _partially -apply_ the `isInSet` function. - -[source,javascript] ----- -var theSet = ["Carel Haverbeke", "Maria van Brussel", - "Donald Duck"]; -function isInSet(set, person) { - return set.indexOf(person.name) > -1; -} - -console.log(ancestry.filter(function(person) { - return isInSet(theSet, person); -})); -// → [{name: "Maria van Brussel", …}, -// {name: "Carel Haverbeke", …}] -console.log(ancestry.filter(isInSet.bind(null, theSet))); -// → … same result ----- - -The call to `bind` returns a function that will call `isInSet` with -`theSet` as first argument, followed by any remaining arguments given -to the bound function. - -(((null)))The first argument, where the example passes `null`, is used -for ((method call))s, similar to the first argument to `apply`. I'll -describe this in more detail in the -link:06_object.html#call_method[next chapter]. - -== Summary == - -Being able to pass function values to other functions is not just a -gimmick but a deeply useful aspect of JavaScript. It allows us to -write computations with “gaps” in them as functions and have the code -that calls these functions fill in those gaps by providing function -values that describe the missing computations. - -Arrays provide a number of useful higher-order methods—`forEach` -to do something with each element in an array, `filter` to build a new -array with some elements filtered out, `map` to build a new array -where each element has been put through a function, and `reduce` to -combine all an array's elements into a single value. - -Functions have an `apply` method that can be used to call them with an -array specifying their arguments. They also have a `bind` method, -which is used to create a partially applied version of the function. - -== Exercises == - -=== Flattening === - -(((flattening (exercise))))(((reduce method)))(((concat -method)))(((array)))Use the `reduce` method in combination with -the `concat` method to “flatten” an array of arrays into a single -array that has all the elements of the input arrays. - -ifdef::interactive_target[] - -// test: no - -[source,javascript] ----- -var arrays = [[1, 2, 3], [4, 5], [6]]; -// Your code here. -// → [1, 2, 3, 4, 5, 6] ----- -endif::interactive_target[] - -=== Mother-child age difference === - -(((ancestry example)))(((age difference (exercise))))(((average -function)))Using the example data set from this chapter, compute the -average age difference between mothers and children (the age of the -mother when the child is born). You can use the `average` function -defined link:05_higher_order.html#average_function[earlier] in this -chapter. - -(((byName object)))Note that not all the mothers mentioned in the data -are themselves present in the array. The `byName` object, which makes -it easy to find a person's object from their name, might be useful -here. - -ifdef::interactive_target[] - -// test: no -// include_code - -[source,javascript] ----- -function average(array) { - function plus(a, b) { return a + b; } - return array.reduce(plus) / array.length; -} - -var byName = {}; -ancestry.forEach(function(person) { - byName[person.name] = person; -}); - -// Your code here. - -// → 31.2 ----- -endif::interactive_target[] - -!!hint!! - -(((age difference (exercise))))(((filter method)))(((map -method)))(((null)))(((average function)))Because not all elements in -the `ancestry` array produce useful data (we can't compute the age -difference unless we know the birth date of the mother), we will have -to apply `filter` in some manner before calling `average`. You could -do it as a first pass, by defining a `hasKnownMother` function and -filtering on that first. Alternatively, you could start by calling -`map` and in your mapping function return either the age difference -or `null` if no mother is known. Then, you can call `filter` to remove -the `null` elements before passing the array to `average`. - -!!hint!! - -=== Historical life expectancy === - -(((life expectancy (exercise))))When we looked up all the people in -our data set that lived more than 90 years, only the latest -generation in the data came out. Let's take a closer look at that -phenomenon. - -(((average function)))Compute and output the average age of the people -in the ancestry data set per century. A person is assigned to a -((century)) by taking their year of death, dividing it by 100, -and rounding it up, as in `Math.ceil(person.died / 100)`. - -ifdef::interactive_target[] - -// test: no - -[source,javascript] ----- -function average(array) { - function plus(a, b) { return a + b; } - return array.reduce(plus) / array.length; -} - -// Your code here. - -// → 16: 43.5 -// 17: 51.2 -// 18: 52.8 -// 19: 54.8 -// 20: 84.7 -// 21: 94 ----- -endif::interactive_target[] - -!!hint!! - -(((life expectancy (exercise))))The essence of this example lies in -((grouping)) the elements of a collection by some aspect of -theirs—splitting the array of ancestors into smaller arrays with the -ancestors for each century. - -(((array)))(((map)))(((object,as map)))During the grouping -process, keep an object that associates ((century)) names (numbers) -with arrays of either person objects or ages. Since we do not know in -advance what categories we will find, we'll have to create them on the -fly. For each person, after computing their century, we test whether -that century was already known. If not, add an array for it. Then add -the person (or age) to the array for the proper century. - -(((for/in loop)))(((average function)))Finally, a `for`/`in` loop can -be used to print the average ages for the individual centuries. - -!!hint!! - -(((grouping)))(((map)))(((object,as map)))(((groupBy function)))For -bonus points, write a function `groupBy` that abstracts the grouping -operation. It should accept as arguments an array and a function that -computes the group for an element in the array and returns an object -that maps group names to arrays of group members. - -=== Every and then some === - -(((predicate function)))(((every and some (exercise))))(((every -method)))(((some method)))(((array,methods)))(((&& operator)))(((|| -operator)))Arrays also come with the standard methods `every` and -`some`. Both take a predicate function that, when called with an array -element as argument, returns true or false. Just like `&&` -returns a true value only when the expressions on both sides are true, -`every` returns true only when the predicate returns true for _all_ -elements of the array. Similarly, `some` returns true as soon as the -predicate returns true for _any_ of the elements. They do not process -more elements than necessary—for example, if `some` finds that the -predicate holds for the first element of the array, it will not look -at the values after that. - -Write two functions, `every` and `some`, that behave like these -methods, except that they take the array as their first argument -rather than being a method. - -ifdef::interactive_target[] - -// test: no - -[source,javascript] ----- -// Your code here. - -console.log(every([NaN, NaN, NaN], isNaN)); -// → true -console.log(every([NaN, NaN, 4], isNaN)); -// → false -console.log(some([NaN, 3, 4], isNaN)); -// → true -console.log(some([2, 3, 4], isNaN)); -// → false ----- -endif::interactive_target[] - -!!hint!! - -(((every and some (exercise))))(((short-circuit evaluation)))(((return -keyword)))The functions can follow a similar pattern to the -link:05_higher_order.html#forEach[definition] of `forEach` at the -start of the chapter, except that they must return immediately (with -the right value) when the predicate function returns false—or true. -Don't forget to put another `return` statement after the loop so that -the function also returns the correct value when it reaches the end of -the array. - -!!hint!! From 18f816ebb652074fb3c9d7608b68e1d43b583faa Mon Sep 17 00:00:00 2001 From: shivam8800 Date: Tue, 5 Sep 2017 04:41:42 +0530 Subject: [PATCH 09/22] review ch 5 --- 04_data.txt | 37 ++----------------------------------- 05_higher_order.txt | 4 ++-- 2 files changed, 4 insertions(+), 37 deletions(-) diff --git a/04_data.txt b/04_data.txt index b28b65a75..b5af36dcb 100644 --- a/04_data.txt +++ b/04_data.txt @@ -1,42 +1,9 @@ -<<<<<<< HEAD -:chap_num: 4 -= Data Structures: Objects and Arrays = - - -On two occasions I have been asked, ‘Pray, -Mr. Babbage, if you put into the machine wrong figures, will the right -answers come out?’ [...] I am not able rightly to apprehend the kind -of confusion of ideas that could provoke such a question. - -#hindi# -mujh se do avsaron pe pucha gaya pray karne ke liye -Mr. Babbage, yadi aap masheen mei galat aankade daalate hain, to sahee -javaab hokar nikalate hain? [...] main iss tarah ki jaanakari ko hasil karne mein saksham nahin hoon -Bhadkane wale saval se vicharon ka bhram ho sakta hain. -____ -======= Chapter 4 Data Structures: Objects and Arrays ->>>>>>> 717a6c22051e8af35ea04d23d9a346730495cad8 -Numbers, Booleans, and strings are the -bricks that ((data)) structures are built from. But you can't make -much of a house out of a single brick. _Objects_ allow us to group -values—including other objects—together and thus build more complex -structures. -<<<<<<< HEAD +Jaise ek house banane k liye hume bahut sari eeton ki jrurat hoti hia thik ussi tarah data structure bhi kuch eeton se banta hia jinka nam hai Numbers, Booleans aur Strings hai.lekin hum ek eet se jayda house ni bna sakte. +objects banate time hum or bhi bahut sare objects use kar sakte hia matalab ek object ko banane k liye hum dusre objects karenge aur isse humare data structure or bhi jayda complex ho jayega. -#hindi# -(((Babbage+++,+++ Charles)))(((object)))(((data structure)))Number, Booleans, aur strings yah sab -bricks ((data)) hote hain. Lekin ham single bricks se house nahi bana sakta hain par _Objects_group values allow -karta hain aur object ke sath ham jyada complex structures bana sakte hain. -======= -# -nambar, booliyan, aur strings hain -eeton ki ((data)) dhache se bana hain lekin aap nahin bana sakte -ek eent mein se adhik ek ghar _objects_ hamen group ke liye anumati deta hai -or vastuon sahit objects—together aur is prakaar adhik jatil structures banaate hain ->>>>>>> 717a6c22051e8af35ea04d23d9a346730495cad8 The programs we have built so far have been seriously hampered by the fact that they were operating only on simple data types. This chapter diff --git a/05_higher_order.txt b/05_higher_order.txt index eba23319a..bb9be4ffd 100644 --- a/05_higher_order.txt +++ b/05_higher_order.txt @@ -19,7 +19,7 @@ karatee hai pareshaan prograamar, badale mein, galatiyon ko shuroo karate hain sthaan pradaan karata hai chhupaane ke lie, unhen khojane ke lie mushkil bana rahee hai - +________________________________________________________________________________finish (((summing example)))Let's briefly go back to the final two example programs in the introduction. The first is self-contained and six @@ -71,7 +71,7 @@ Agar hum 'sum' aur 'range' ki defination ka size count kare to, Second program b Numbers ki range loops aur counters par depend ni karti wo keval ranges and sums par depend karti hai. 'sum' aur 'range' ki definitions mei abhi bhi loops aur counters available hai.kyuki isse hume pure program ka flow pta chlta hai aur isse kisi bhi concept ko aaram se smjh sakte hai. - +________________________________________________________________________________finish == Abstraction == From 6952ac586702cb09f50b0301ec56f063f16c3178 Mon Sep 17 00:00:00 2001 From: dhannukumar Date: Tue, 5 Sep 2017 05:18:32 +0530 Subject: [PATCH 10/22] some changes --- 05_higher_order.txt | 43 +++++++------------------------------------ 1 file changed, 7 insertions(+), 36 deletions(-) diff --git a/05_higher_order.txt b/05_higher_order.txt index bb9be4ffd..5570c382e 100644 --- a/05_higher_order.txt +++ b/05_higher_order.txt @@ -9,23 +9,13 @@ programmers, in turn, tend to introduce mistakes (_((bug))s_) into programs. A large program also provides a lot of space for these bugs to hide, making them hard to find. -///** HINDI **// +///** HINDI **// -(((prograam aakaar))) ek bada kaaryakram mahanga kaaryakram -hai, na ki bas kyonki us samay ke nirmaan ke lie leta hai aakaar lagabhag -hamesha shaamil hota hai (jatilata)), aur jatilata prograamar ko bhramit -karatee hai pareshaan prograamar, badale mein, galatiyon ko shuroo karate hain -(_ ((bag)) s_) mein kaaryakram. ek bada kaaryakram in bagon ke lie bahut saare -sthaan pradaan karata hai chhupaane ke lie, unhen khojane ke lie mushkil bana -rahee hai +(((program size))) yah program bada aur costly hain lekin isse build karne me time lagta hain, +size hamesha programmer ko confused karta hain. Bugs program main mistakes ko dikhata hain. +Ek bada program bugs ke liye bada space deta hain jisse usse find karne mei muskile hoti hain. -________________________________________________________________________________finish - -(((summing example)))Let's briefly go back to the final two example -programs in the introduction. The first is self-contained and six -lines long. -//**HINDI**// Hum ab 2 example lenge jo humne Introduction chapter mei pade the. To pehla example six lines lamba aur self contained hai. @@ -39,9 +29,6 @@ while (count <= 10) { console.log(total); ---- -The second relies on two external functions and is one line long. - -//**HINDI**// Aur seccond 2 bahari function par depend karta hhai aur wo 1 line ka hai. @@ -50,23 +37,7 @@ Aur seccond 2 bahari function par depend karta hhai aur wo 1 line ka hai. console.log(sum(range(1, 10))); ---- -Which one is more likely to contain a bug? -If we count the size of the definitions of `sum` and -`range`, the second program is also big—even bigger than the first. -But still, I'd argue that it is more likely to be correct. -It is more likely to be correct because the solution is expressed in a ((vocabulary)) that -corresponds to the problem being solved. Summing a range of -numbers isn't about loops and counters. It is about ranges and sums. - - -The definitions of this vocabulary (the functions `sum` and `range`) -will still involve loops, counters, and other incidental details. But -because they are expressing simpler concepts than the program as a -whole, they are easier to get right. - - -//**HINDI**// -Upper wale dono examples mei se kismei bug hai mtlb todi bahut galti hai? +Upper wale dono examples mei se kisi mei bug hai mtlb todi bahut galti hai? Agar hum 'sum' aur 'range' ki defination ka size count kare to, Second program bada hai first se.lekin hum abhi bhi second example ko correct kahenge.kyuki uska solution problem solve krne se related karta hai aur kam code bhi hai. Numbers ki range loops aur counters par depend ni karti wo keval ranges and sums par depend karti hai. @@ -408,7 +379,7 @@ data storage and communication format on the Web. (((array)))(((object)))(((quoting,in JSON)))(((comment)))JSON is similar to JavaScript's way of writing arrays and objects, with a few restrictions. All property names have to be surrounded by double quotes, and -only simple data expressions are allowed—no function calls, +only simple data expressions are allowed—no function calls, variables, or anything that involves actual computation. Comments are not allowed in JSON. @@ -1052,7 +1023,7 @@ that maps group names to arrays of group members. method)))(((some method)))(((array,methods)))(((&& operator)))(((|| operator)))Arrays also come with the standard methods `every` and `some`. Both take a predicate function that, when called with an array -element as argument, returns true or false. Just like `&&` +element as argument, returns true or false. Just like `&&` returns a true value only when the expressions on both sides are true, `every` returns true only when the predicate returns true for _all_ elements of the array. Similarly, `some` returns true as soon as the From 3fb5d8b25225e97334fc7e7bd14154a66968ba61 Mon Sep 17 00:00:00 2001 From: dhannukumar Date: Tue, 5 Sep 2017 08:38:57 +0530 Subject: [PATCH 11/22] translate one paragraph --- 04_data.txt | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/04_data.txt b/04_data.txt index b5af36dcb..ef10986bc 100644 --- a/04_data.txt +++ b/04_data.txt @@ -31,6 +31,13 @@ you decide to work through the examples in another environment, be sure to first download the full code for this chapter from the sandbox page. +#hindi# +Online coding book ke liye, +(http://eloquentjavascript.net/code[_eloquentjavascript.net/code_]) +agar apne decide kiya hain dusre environment example mei kaam karne ka +to pehle iss chapter ka pura code download karo sandbox page se. + + endif::book_target[] == The weresquirrel == @@ -49,6 +56,8 @@ and disoriented, he has taken to locking the doors and windows of his room at night and putting a few walnuts on the floor to keep himself busy. + + image::img/weresquirrel.png[alt="The weresquirrel"] That takes care of the cat and oak problems. But Jacques still suffers From 6d5f36e953f3e1592fcb521c84e6cc23f32bef4a Mon Sep 17 00:00:00 2001 From: courage Date: Tue, 5 Sep 2017 09:17:45 +0530 Subject: [PATCH 12/22] resive file 4th file --- 05_higher_order.txt | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/05_higher_order.txt b/05_higher_order.txt index e29c4c402..e9b0cd29f 100644 --- a/05_higher_order.txt +++ b/05_higher_order.txt @@ -10,9 +10,10 @@ programs. A large program also provides a lot of space for these bugs to hide, making them hard to find. -///** HINDI **// -(((prograam aakaar))) ek bada kaaryakram mahanga kaaryakram +///** HINDI **// + +(((program size))) ek bada program mahanga kaaryakram hai, na ki bas kyonki us samay ke nirmaan ke lie leta hai aakaar lagabhag hamesha shaamil hota hai (jatilata)), aur jatilata prograamar ko bhramit karatee hai pareshaan prograamar, badale mein, galatiyon ko shuroo karate hain @@ -394,7 +395,7 @@ data storage and communication format on the Web. (((array)))(((object)))(((quoting,in JSON)))(((comment)))JSON is similar to JavaScript's way of writing arrays and objects, with a few restrictions. All property names have to be surrounded by double quotes, and -only simple data expressions are allowed—no function calls, +only simple data expressions are allowed—no function calls, variables, or anything that involves actual computation. Comments are not allowed in JSON. @@ -1038,7 +1039,7 @@ that maps group names to arrays of group members. method)))(((some method)))(((array,methods)))(((&& operator)))(((|| operator)))Arrays also come with the standard methods `every` and `some`. Both take a predicate function that, when called with an array -element as argument, returns true or false. Just like `&&` +element as argument, returns true or false. Just like `&&` returns a true value only when the expressions on both sides are true, `every` returns true only when the predicate returns true for _all_ elements of the array. Similarly, `some` returns true as soon as the From dab7f2d2db1585732791ef8e77a320fbbafe1647 Mon Sep 17 00:00:00 2001 From: ranjan3606 Date: Tue, 5 Sep 2017 09:37:33 +0530 Subject: [PATCH 13/22] 1 pragraph change --- 03_functions.txt | 25 ++++++++++++ 05_higher_order.txt | 99 ++++++++++++++++++++++----------------------- 06_object.txt | 29 +++++++++++-- 3 files changed, 99 insertions(+), 54 deletions(-) diff --git a/03_functions.txt b/03_functions.txt index d7aed41bb..105f019df 100644 --- a/03_functions.txt +++ b/03_functions.txt @@ -19,11 +19,20 @@ in a value has many uses. It is a tool to structure larger programs, to reduce repetition, to associate names with subprograms, and to isolate these subprograms from each other. +(function value, jaise, ki chetawani aur uhne kaise call krna hai. function bread or butter ka mixture hota h wese hi Javascript me programming jruri hai.jo program ki value hai jab usko concept ke andr rakhte hai to wo kai tarike se use hoti hai. ye bade program bnane ka tool hai, ye repetation ko kam krta hai, ye sabprogram ke naam ke saath sahyogita krata hai, aur in programo ko ek dusre se alag alag rakhna jaisi chije.) + + + (((human language)))The most obvious application of functions is defining new ((vocabulary)). Creating new words in regular, human-language prose is usually bad style. But in programming, it is indispensable. +(sabse jahir upyog function ki ye hai ki nye sabad ko define krta hai jo ki human language hai. rojana nye word banana, human laguage me gaap sadharan tah galat andaj/tarika hai. par programing me ye aavayshak hai.) + + + + (((abstraction)))Typical adult English speakers have some 20,000 words in their vocabulary. Few programming languages come with 20,000 commands built in. And the vocabulary that _is_ available tends to be @@ -31,6 +40,12 @@ more precisely defined, and thus less flexible, than in human language. Therefore, we usually _have_ to add some of our own vocabulary to avoid repeating ourselves too much. +(ek comman adult ke sabadkosh me genrally 20 hajar shabad hote hai. kuch programming languages bh 20 hajar command ke define hote hai. +aur jo shabadkosh avalble hota hai wo aur thik tarike se define hota hai, aur isliye human laguage se kam flexibble hota hai. isliye usually apni sabadkosh ko add krte hai jisse hum apni baar dohrane ki aadat ka virodh kar sake.) + + + + == Defining a function == (((square)))(((function,definition)))A function definition is just a @@ -39,6 +54,9 @@ happens to be a function. For example, the following code defines the variable `square` to refer to a function that produces the square of a given number: +jo function hai wo sirf ek dafination hai jo regular varible me given value ko function sabit karta hai. udharan ke liye: diya hua code ek square variable ko define karta hai jo ye refer karta hai ki given number ka square kar denewala function hai. + + [source,javascript] ---- var square = function(x) { @@ -59,6 +77,13 @@ the function is called. The function body must always be wrapped in braces, even when it consists of only a single ((statement)) (as in the previous example). +function ek experssion/abhivyakat hai jo ki function ke keyword se shuru hai, function ne ((parameter))s_ (in this case, only `x`) aur +a _body_, ko set kar rakha hai, jisme statement moujood hai ki jisse wo executed hota hai jab function ko kaha jata hai. + + + + + (((power example)))A function can have multiple parameters or no parameters at all. In the following example, `makeNoise` does not list any parameter names, whereas `power` lists two: diff --git a/05_higher_order.txt b/05_higher_order.txt index ef6edb5ed..921349a11 100644 --- a/05_higher_order.txt +++ b/05_higher_order.txt @@ -1,33 +1,5 @@ -:chap_num: 5 -:prev_link: 04_data -:next_link: 06_object -:load_files: ["code/ancestry.js", "code/chapter/05_higher_order.js", "code/intro.js"] -:zip: node/html - -= Higher-Order Functions = - -ifdef::interactive_target[] - -[chapterquote="true"] -[quote, Master Yuan-Ma, The Book of Programming] -____ -Tzu-li and Tzu-ssu were -boasting about the size of their latest programs. ‘Two-hundred -thousand lines,’ said Tzu-li, ‘not counting comments!’ Tzu-ssu -responded, ‘Pssh, mine is almost a *million* lines already.’ Master -Yuan-Ma said, ‘My best program has five hundred lines.’ Hearing this, -Tzu-li and Tzu-ssu were enlightened. -____ - -endif::interactive_target[] - -[chapterquote="true"] -[quote, C.A.R. Hoare, 1980 ACM Turing Award Lecture] -____ -(((Hoare+++,+++ C.A.R.)))There are two ways of constructing a software -design: One way is to make it so simple that there are obviously no -deficiencies, and the other way is to make it so complicated that -there are no obvious deficiencies. +Chapter 5 +Higher-Order Functions[quote, Master Yuan-Ma, The Book of Programming] ____ (((program size)))A large program is a costly program, and not just @@ -37,32 +9,48 @@ programmers, in turn, tend to introduce mistakes (_((bug))s_) into programs. A large program also provides a lot of space for these bugs to hide, making them hard to find. -(((summing example)))Let's briefly go back to the final two example -programs in the introduction. The first is self-contained and six -lines long. -[source,javascript] ----- -var total = 0, count = 1; -while (count <= 10) { - total += count; - count += 1; -} -console.log(total); ----- +///** HINDI **// + +(((prograam aakaar))) ek bada kaaryakram mahanga kaaryakram +hai, na ki bas kyonki us samay ke nirmaan ke lie leta hai aakaar lagabhag +hamesha shaamil hota hai (jatilata)), aur jatilata prograamar ko bhramit +karatee hai pareshaan prograamar, badale mein, galatiyon ko shuroo karate hain +(_ ((bag)) s_) mein kaaryakram. ek bada kaaryakram in bagon ke lie bahut saare +sthaan pradaan karata hai chhupaane ke lie, unhen khojane ke lie mushkil bana +rahee hai + + + +(((summing example)))Let's briefly go back to the final two example programs +in the introduction. The first is self-contained and six lines long. + +///** HINDII **// +aaiye do udharan ko bare me jante hai. pehla example 6 line lamba hai + + +[source,javascript] ---- var total = 0, count = 1; while (count <= 10) { +total += count; count += 1; } console.log(total); ---- The second relies on two external functions and is one line long. -[source,javascript] ----- -console.log(sum(range(1, 10))); ----- +[source,javascript] ---- console.log(sum(range(1, 10))); ---- + +Which one is more likely to contain a bug? +///** HINDI **// +kaun sa ek bag ke hone kee sambhaavana hai? -Which one is more likely to contain a bug? (((program size)))If we count the size of the definitions of `sum` and -`range`, the second program is also big—even bigger than the first. -But still, I'd argue that it is more likely to be correct. +`range`, the second program is also big—even bigger than the first. But still, +I'd argue that it is more likely to be correct. ----------- + +///** HINDI **// (((prograam ka aakaar))) yadi ham `sum` ke paribhaashaon ka +aakaar maanate hain aur `range`, doosara prograam bhi bada hai-pahale ke +tulana mein bhi bada hai lekin phir bhi, main tark krta hoon ki yah sahi +hone ke adhik sambhaavana hai. + + (((abstraction)))(((domain-specific language)))It is more likely to be correct because the solution is expressed in a ((vocabulary)) that @@ -74,12 +62,23 @@ will still involve loops, counters, and other incidental details. But because they are expressing simpler concepts than the program as a whole, they are easier to get right. + + + == Abstraction == In the context of programming, these kinds of vocabularies are usually called _((abstraction))s_. Abstractions hide details and give us the ability to talk about problems at a higher (or more abstract) level. +///** HINDI **// +programming ke sandarbh mevocubularies ke in prakar ko aam tour pe +((abstraction)) kaha jata hai. Abstractions vivaran chhipaane ke liye aur +hamen ek kuch (ya adhik abstract) samasyaon ke baare me janne ka sahi tarika hai +________________________________________________________________________________finish + + + (((recipe analogy)))(((pea soup)))As an analogy, compare these two recipes for pea soup: @@ -1096,4 +1095,4 @@ Don't forget to put another `return` statement after the loop so that the function also returns the correct value when it reaches the end of the array. -!!hint!! +!!hint!! \ No newline at end of file diff --git a/06_object.txt b/06_object.txt index 82dd87986..ec75122e0 100644 --- a/06_object.txt +++ b/06_object.txt @@ -15,14 +15,20 @@ with them. You wanted a banana but what you got was a gorilla holding the banana and the entire jungle. ____ -(((Armstrong+++,+++ Joe)))(((object)))(((holy war)))When a programmer -says “object”, this is a loaded term. In my profession, objects are a -way of life, the subject of holy wars, and a beloved buzzword that -still hasn't quite lost its power. +(((Armstrong+++,+++ Joe)))(((object)))(((holy war)))When a programmer says “object”, this is a loaded term. In my profession, objects are a +way of life, the subject of holy wars, and a beloved buzzword that still hasn't quite lost its power. + +///** HINDI **// +jab ek programmer kehta hai ki "object" yah ek loaded term hai. mera beloved buzzworde peshe me, object ek rasta hai hamre life ka,aur ye holy wars ka subject hai,aur ek pyari behas hai ki abhi apni power kho kar bh kafi chije kar rha hai. + To an outsider, this is probably a little confusing. Let's start with a brief ((history)) of objects as a programming construct. +///** HINDI **// +ek bahari log ke liye, ye shayad thoda confusing hai.aiye shuru karte hai or jante hai iske program ke history aur iske nirman ke bare me.. + + == History == (((isolation)))(((history)))(((object-oriented programming)))(((object)))This story, like most programming stories, starts with the @@ -31,6 +37,13 @@ made manageable by separating it into small compartments that are isolated from each other. These compartments have ended up with the name _objects_. +///** HINDI **// +ye story jo hai ek programming ki tarah hai, shuru karte hai problem ki uljhan ke sath. ek philosophy yah hai ki uljhan ko alag karake manageable banaaya ja sakata hai ye ek chote compartments jo ki alag rehta hai ek dusre se. ye compartments mein name _objects ke saath samaapt ho gaya hai. + + + + + [[interface]] (((complexity)))(((encapsulation)))(((method)))(((interface)))An object is a hard shell that hides the gooey complexity inside it @@ -40,6 +53,14 @@ The idea is that the interface is relatively simple and all the complex things going on _inside_ the object can be ignored when working with it. + + +///** HINDI **// +ek object hard shell ki tarah hai jo andhruni jatilta ke andar le jata hai ye aur + + + + image::img/object.jpg[alt="A simple interface can hide a lot of complexity.",width="6cm"] As an example, you can imagine an object that provides an interface to From 0e62e6855e619b6d99fc93cc7458338d7db6b24d Mon Sep 17 00:00:00 2001 From: courage Date: Tue, 5 Sep 2017 10:35:39 +0530 Subject: [PATCH 14/22] review --- 05_higher_order.txt | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/05_higher_order.txt b/05_higher_order.txt index ef7b0a22c..c848629c7 100644 --- a/05_higher_order.txt +++ b/05_higher_order.txt @@ -2,22 +2,20 @@ Chapter 5 Higher-Order Functions[quote, Master Yuan-Ma, The Book of Programming] ____ -(((program size)))A large program is a costly program, and not just -because of the time it takes to build. Size almost always involves -((complexity)), and complexity confuses programmers. Confused -programmers, in turn, tend to introduce mistakes (_((bug))s_) into -programs. A large program also provides a lot of space for these bugs -to hide, making them hard to find. -<<<<<<< HEAD + (((program size)))ek bada kaaryakram mahanga kaaryakram hai, na ki bas kyonki us samay ke nirmaan ke lie leta hai aakaar lagabhag hamesha shaamil hota hai (complexity)), aur jatilata prograamar ko bhramit karatee hai pareshaan -prograamar, badale mein, galatiyon ko shuroo karate hain (_ ((bag)) s_) mein -kaaryakram. ek bada kaaryakram in bagon ke lie bahut saare sthaan pradaan karata hai -chhipaane ke lie, unhen dhoondhana kathin bana deta hai +prograamar, badale mein, galatiyon ko shuroo karate hain (_ ((bug))s_) mein +kaaryakram. ek bada kaaryakram in space ke lie bahut saare sthaan pradan karata hai +chhipaane ke liye, unhen dhoondhana kathin bana deta hai. + + +<<<<<<< HEAD + ///** HINDI **// @@ -48,7 +46,7 @@ Hum ab 2 example lenge jo humne Introduction chapter mei pade the. To pehla example six lines lamba aur self contained hai. >>>>>>> 3fb5d8b25225e97334fc7e7bd14154a66968ba61 -///** HINDI **// +///** HINDI **// (((prograam aakaar))) ek bada kaaryakram mahanga kaaryakram hai, na ki bas kyonki us samay ke nirmaan ke lie leta hai aakaar lagabhag @@ -75,8 +73,8 @@ Aur seccond 2 bahari function par depend karta hhai aur wo 1 line ka hai. [source,javascript] ---- console.log(sum(range(1, 10))); ---- -Which one is more likely to contain a bug? -///** HINDI **// +Which one is more likely to contain a bug? +///** HINDI **// kaun sa ek bag ke hone kee sambhaavana hai? <<<<<<< HEAD @@ -114,9 +112,9 @@ In the context of programming, these kinds of vocabularies are usually called _((abstraction))s_. Abstractions hide details and give us the ability to talk about problems at a higher (or more abstract) level. -///** HINDI **// +///** HINDI **// programming ke sandarbh mevocubularies ke in prakar ko aam tour pe -((abstraction)) kaha jata hai. Abstractions vivaran chhipaane ke liye aur +((abstraction)) kaha jata hai. Abstractions vivaran chhipaane ke liye aur hamen ek kuch (ya adhik abstract) samasyaon ke baare me janne ka sahi tarika hai ________________________________________________________________________________finish @@ -1138,4 +1136,4 @@ Don't forget to put another `return` statement after the loop so that the function also returns the correct value when it reaches the end of the array. -!!hint!! \ No newline at end of file +!!hint!! From fa9e7880a667810271d9eb38b3035bb18ad2b3f0 Mon Sep 17 00:00:00 2001 From: ranjan3606 Date: Tue, 5 Sep 2017 11:02:21 +0530 Subject: [PATCH 15/22] i have review 4th chapter --- 04_data.txt | 27 ++++++--------------------- 05_higher_order.txt | 43 ++++++++++++++++++++++++++++--------------- 2 files changed, 34 insertions(+), 36 deletions(-) diff --git a/04_data.txt b/04_data.txt index ef10986bc..a7ebd7b1e 100644 --- a/04_data.txt +++ b/04_data.txt @@ -5,33 +5,18 @@ Jaise ek house banane k liye hume bahut sari eeton ki jrurat hoti hia thik ussi objects banate time hum or bhi bahut sare objects use kar sakte hia matalab ek object ko banane k liye hum dusre objects karenge aur isse humare data structure or bhi jayda complex ho jayega. -The programs we have built so far have been seriously hampered by the -fact that they were operating only on simple data types. This chapter -will add a basic understanding of data structures to your toolkit. By -the end of it, you'll know enough to start writing some useful -programs. - -#hindi# Ab tak hamne jo program banaye hain, usse baadhit kiya gaya hai fact yah hai ki keval simple data types par kaam kar rahe the. yah chapter -aapake basic data structures ko samjhne me madad karenga. iske last mei app itne able ho jayenge ki app -ek useful program start kar sakte hain. +aapake basic data structures ko samjhne me madad karenga. iske last mei app +itne able ho jayenge ki app ek useful program start kar sakte hain. -The chapter will work through a more or less realistic programming -example, introducing concepts as they apply to the problem at hand. -The example code will often build on functions and variables that were -introduced earlier in the text. -ifdef::book_target[] +chapter adhik ya kam yatarthvadi prograaming ke madhyam se kaam karega, +introduction ko pesh karane ke saath-saath uski samsya hamare hatho me +hoti hain. udaaharan kod aksar functions and variables par banaya jayega +ki jaise pehle text me introduced kiya gya tha. -(((sandbox)))The online coding sandbox for the book -(http://eloquentjavascript.net/code[_eloquentjavascript.net/code_]) -provides a way to run code in the context of a specific chapter. If -you decide to work through the examples in another environment, be -sure to first download the full code for this chapter from the -sandbox page. -#hindi# Online coding book ke liye, (http://eloquentjavascript.net/code[_eloquentjavascript.net/code_]) agar apne decide kiya hain dusre environment example mei kaam karne ka diff --git a/05_higher_order.txt b/05_higher_order.txt index e697c0abb..c69de2f63 100644 --- a/05_higher_order.txt +++ b/05_higher_order.txt @@ -95,21 +95,34 @@ hamen ek kuch (ya adhik abstract) samasyaon ke baare me janne ka sahi tarika hai ________________________________________________________________________________finish - -(((recipe analogy)))(((pea soup)))As an analogy, compare these two -recipes for pea soup: - -____ -Put 1 cup of dried peas per person into a container. Add water until -the peas are well covered. Leave the peas in water for at least 12 hours. -Take the peas out of the water and put them in a cooking pan. Add 4 -cups of water per person. Cover the pan and keep the peas -simmering for two hours. Take half an onion per person. Cut it into -pieces with a knife. Add it to the peas. Take a stalk of celery per -person. Cut it into pieces with a knife. Add it to the peas. Take a -carrot per person. Cut it into pieces. With a knife! Add it to the -peas. Cook for 10 more minutes. -____ +(((recipe analogy)))(((pea soup)))As an analogy, compare these two recipes for +pea soup: + +///** HINDI **// +(((recipe analogy))) (((matar ka soop)) ek samaanata ke roop mein, +in donon kee tulana karen matar ka soop ke lie vyanjanon: + +____ Put 1 cup of dried peas per person into a container. Add water until the +peas are well covered. Leave the peas in water for at least 12 hours. Take the +peas out of the water and put them in a cooking pan. Add 4 cups of water per +person. Cover the pan and keep the peas simmering for two hours. Take half an +onion per person. Cut it into pieces with a knife. Add it to the peas. Take a +stalk of celery per person. Cut it into pieces with a knife. Add it to the +peas. Take a carrot per person. Cut it into pieces. With a knife! Add it to +the peas. Cook for 10 more minutes. ____ + + + +///** HINDI **// 1 container mein prati vyakti ke liye sukhe matar ke daane rakho 1 kap me. +jab tak matar pani me achchhee tarah se add ho jaata hai. kam se kam +12 ghante ke liye pani mein matar chhod den. matar ko paanee se baahar le jao +aur unhen khaana pakaane ke pain mein daal den. 4 add prati vyakti paanee ka +kap pain ko kavar karen aur matar rakhen do ghante ke lie ubaal prati vyakti +aadha pyaaj len ise kaat len ek chaakoo ke saath tukade ise matar mein add +prati ajavain ka danthal len vyakti. ise chaku se tukadon mein kaat len ise +matar mein add ek lo prati vyakti gaajar ise tukadon mein kaaten. chaakoo ke +saath! ise add matar. 10 minut aur pakaye. +________________________________________________________________________________finish And the second recipe: ____ From e72882953bd554b279cae81ec55652bf603ece77 Mon Sep 17 00:00:00 2001 From: courage Date: Tue, 5 Sep 2017 11:19:17 +0530 Subject: [PATCH 16/22] change one pera --- 04_data.txt | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/04_data.txt b/04_data.txt index e4c468202..26418a77e 100644 --- a/04_data.txt +++ b/04_data.txt @@ -37,6 +37,14 @@ you decide to work through the examples in another environment, be sure to first download the full code for this chapter from the sandbox page. +(((sandbox)))kitaab ke lie online koding sandbox +(http://eloquentjavascript.net/code[_eloquentjavascript.net/code_]) +ek vishisht adhyaay ke sandarbh mein code chalaane ka ek tareeka pradaan karata hai agar +aap kisee any vaataavaran mein udaaharanon ke maadhyam se kaam karane ka nirnay lete hain,hona +pahale se is adhyaay ke lie complite kod daunalod karana sunishchit karen +sandbox page. + + #hindi# Online coding book ke liye, (http://eloquentjavascript.net/code[_eloquentjavascript.net/code_]) From 06be58ce34f0b36c5b0cbccda429f1c546bbca0b Mon Sep 17 00:00:00 2001 From: ranjan3606 Date: Tue, 5 Sep 2017 11:38:11 +0530 Subject: [PATCH 17/22] change the paragraph --- 05_higher_order.txt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/05_higher_order.txt b/05_higher_order.txt index a6f0b5376..d7edd7c12 100644 --- a/05_higher_order.txt +++ b/05_higher_order.txt @@ -137,8 +137,9 @@ the peas. Cook for 10 more minutes. ____ -///** HINDI **// 1 container mein prati vyakti ke liye sukhe matar ke daane rakho 1 kap me. -jab tak matar pani me achchhee tarah se add ho jaata hai. kam se kam +///** HINDI **// +1 container mein prati vyakti ke liye sukhe matar ke daane rakho +1 kap me.jab tak matar pani me achchhee tarah se add ho jaata hai. kam se kam 12 ghante ke liye pani mein matar chhod den. matar ko paanee se baahar le jao aur unhen khaana pakaane ke pain mein daal den. 4 add prati vyakti paanee ka kap pain ko kavar karen aur matar rakhen do ghante ke lie ubaal prati vyakti From 51c54364ea688f9dff8625c28258b649c4287e85 Mon Sep 17 00:00:00 2001 From: ranjan3606 Date: Tue, 5 Sep 2017 11:41:14 +0530 Subject: [PATCH 18/22] 2 paragraph change --- 04_data.txt | 12 ++++++++++++ 05_higher_order.txt | 4 ++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/04_data.txt b/04_data.txt index 066b00622..88868255f 100644 --- a/04_data.txt +++ b/04_data.txt @@ -27,6 +27,18 @@ ifdef::book_target[] >>>>>>> 0e62e6855e619b6d99fc93cc7458338d7db6b24d +<<<<<<< HEAD +(((sandbox)))kitaab ke lie online koding sandbox +(http://eloquentjavascript.net/code[_eloquentjavascript.net/code_]) +ek vishisht adhyaay ke sandarbh mein code chalaane ka ek tareeka pradaan karata hai agar +aap kisee any vaataavaran mein udaaharanon ke maadhyam se kaam karane ka nirnay lete hain,hona +pahale se is adhyaay ke lie complite kod daunalod karana sunishchit karen +sandbox page. + + +#hindi# +======= +>>>>>>> 4e1a107f8eb44f93eedde72c200b170df2a76d8c Online coding book ke liye, (http://eloquentjavascript.net/code[_eloquentjavascript.net/code_]) agar apne decide kiya hain dusre environment example mei kaam karne ka diff --git a/05_higher_order.txt b/05_higher_order.txt index d7edd7c12..24a09e332 100644 --- a/05_higher_order.txt +++ b/05_higher_order.txt @@ -126,14 +126,14 @@ pea soup: (((recipe analogy))) (((matar ka soop)) ek samaanata ke roop mein, in donon kee tulana karen matar ka soop ke lie vyanjanon: -____ Put 1 cup of dried peas per person into a container. Add water until the +Put 1 cup of dried peas per person into a container. Add water until the peas are well covered. Leave the peas in water for at least 12 hours. Take the peas out of the water and put them in a cooking pan. Add 4 cups of water per person. Cover the pan and keep the peas simmering for two hours. Take half an onion per person. Cut it into pieces with a knife. Add it to the peas. Take a stalk of celery per person. Cut it into pieces with a knife. Add it to the peas. Take a carrot per person. Cut it into pieces. With a knife! Add it to -the peas. Cook for 10 more minutes. ____ +the peas. Cook for 10 more minutes. From 53391eed0f5790a7dd243dfba20684c61d88a92f Mon Sep 17 00:00:00 2001 From: courage Date: Tue, 5 Sep 2017 11:44:54 +0530 Subject: [PATCH 19/22] change one pera --- 04_data.txt | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/04_data.txt b/04_data.txt index 88868255f..0f17131f1 100644 --- a/04_data.txt +++ b/04_data.txt @@ -7,13 +7,13 @@ objects banate time hum or bhi bahut sare objects use kar sakte hia matalab ek o Ab tak hamne jo program banaye hain, usse baadhit kiya gaya hai fact yah hai ki keval simple data types par kaam kar rahe the. yah chapter -aapake basic data structures ko samjhne me madad karenga. iske last mei app +aapake basic data structures ko samjhne me madad karenga. iske last mei app itne able ho jayenge ki app ek useful program start kar sakte hain. <<<<<<< HEAD chapter adhik ya kam yatarthvadi prograaming ke madhyam se kaam karega, -introduction ko pesh karane ke saath-saath uski samsya hamare hatho me +introduction ko pesh karane ke saath-saath uski samsya hamare hatho me hoti hain. udaaharan kod aksar functions and variables par banaya jayega ki jaise pehle text me introduced kiya gya tha. ======= @@ -53,6 +53,11 @@ endif::book_target[] between eight and ten in the evening, ((Jacques)) finds himself transforming into a small furry rodent with a bushy tail. +(((weresquirrel example)))(((lycanthropy)))bahut pahale aur phir, aamataur par +shyam ko eight aur ten ke beech,((Jacques)) apane aap paata hai +ek jangalee poonchh ke saath ek chhote se pyaare krntak mein badalane. + + On one hand, Jacques is quite glad that he doesn't have classic lycanthropy. Turning into a squirrel tends to cause fewer problems than turning into a wolf. Instead of having to worry about From 208b43280f619a12684210e5fd3c31847cd8d945 Mon Sep 17 00:00:00 2001 From: ranjan3606 Date: Tue, 5 Sep 2017 11:44:55 +0530 Subject: [PATCH 20/22] change --- 05_higher_order.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/05_higher_order.txt b/05_higher_order.txt index 24a09e332..a3d746b23 100644 --- a/05_higher_order.txt +++ b/05_higher_order.txt @@ -122,6 +122,7 @@ ________________________________________________________________________________ (((recipe analogy)))(((pea soup)))As an analogy, compare these two recipes for pea soup: + ///** HINDI **// (((recipe analogy))) (((matar ka soop)) ek samaanata ke roop mein, in donon kee tulana karen matar ka soop ke lie vyanjanon: @@ -136,7 +137,6 @@ peas. Take a carrot per person. Cut it into pieces. With a knife! Add it to the peas. Cook for 10 more minutes. - ///** HINDI **// 1 container mein prati vyakti ke liye sukhe matar ke daane rakho 1 kap me.jab tak matar pani me achchhee tarah se add ho jaata hai. kam se kam From 4d2806f055924bbf1f37ef9ac3b691c528f33566 Mon Sep 17 00:00:00 2001 From: ranjan3606 Date: Tue, 5 Sep 2017 11:56:16 +0530 Subject: [PATCH 21/22] review --- 04_data.txt | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/04_data.txt b/04_data.txt index 88868255f..e7e8b9d17 100644 --- a/04_data.txt +++ b/04_data.txt @@ -23,22 +23,14 @@ udaaharan code praayah functions aur veriebal par banaayega jo ki the pahale paath mein pesh kiya -ifdef::book_target[] ->>>>>>> 0e62e6855e619b6d99fc93cc7458338d7db6b24d - - -<<<<<<< HEAD (((sandbox)))kitaab ke lie online koding sandbox (http://eloquentjavascript.net/code[_eloquentjavascript.net/code_]) ek vishisht adhyaay ke sandarbh mein code chalaane ka ek tareeka pradaan karata hai agar -aap kisee any vaataavaran mein udaaharanon ke maadhyam se kaam karane ka nirnay lete hain,hona -pahale se is adhyaay ke lie complite kod daunalod karana sunishchit karen +aap kaise bh any vatavaran mein udharan ke madhyam se kaam krane ka nirnay lete hain,hona +pehale se is adhyay ke liye complite code download karke sunishchit karen sandbox page. -#hindi# -======= ->>>>>>> 4e1a107f8eb44f93eedde72c200b170df2a76d8c Online coding book ke liye, (http://eloquentjavascript.net/code[_eloquentjavascript.net/code_]) agar apne decide kiya hain dusre environment example mei kaam karne ka From 998860cecc725dab3b8315136de421c7bca9b2c7 Mon Sep 17 00:00:00 2001 From: courage Date: Tue, 5 Sep 2017 12:16:12 +0530 Subject: [PATCH 22/22] revew --- 05_higher_order.txt | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/05_higher_order.txt b/05_higher_order.txt index a3d746b23..b20540306 100644 --- a/05_higher_order.txt +++ b/05_higher_order.txt @@ -121,23 +121,14 @@ ________________________________________________________________________________ (((recipe analogy)))(((pea soup)))As an analogy, compare these two recipes for pea soup: - + ///** HINDI **// (((recipe analogy))) (((matar ka soop)) ek samaanata ke roop mein, in donon kee tulana karen matar ka soop ke lie vyanjanon: -Put 1 cup of dried peas per person into a container. Add water until the -peas are well covered. Leave the peas in water for at least 12 hours. Take the -peas out of the water and put them in a cooking pan. Add 4 cups of water per -person. Cover the pan and keep the peas simmering for two hours. Take half an -onion per person. Cut it into pieces with a knife. Add it to the peas. Take a -stalk of celery per person. Cut it into pieces with a knife. Add it to the -peas. Take a carrot per person. Cut it into pieces. With a knife! Add it to -the peas. Cook for 10 more minutes. - -///** HINDI **// +///** HINDI **// 1 container mein prati vyakti ke liye sukhe matar ke daane rakho 1 kap me.jab tak matar pani me achchhee tarah se add ho jaata hai. kam se kam 12 ghante ke liye pani mein matar chhod den. matar ko paanee se baahar le jao