JavaScript Comparison and Logical Operators - W3Schools
文章推薦指數: 80 %
JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. Syntax. variablename = (condition) ? value1:value2 ... Tutorials References Exercises Videos Menu Login Website GetCertified ProNEW HTML CSS JAVASCRIPT SQL PYTHON PHP BOOTSTRAP HOWTO W3.CSS JAVA JQUERY C C++ C# R React Darkmode Darkcode × Tutorials HTMLandCSS LearnHTML LearnCSS LearnRWD LearnBootstrap LearnW3.CSS LearnColors LearnIcons LearnGraphics LearnSVG LearnCanvas LearnHowTo LearnSass DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery JavaScript LearnJavaScript LearnjQuery LearnReact LearnAngularJS LearnJSON LearnAJAX LearnAppML LearnW3.JS Programming LearnPython LearnJava LearnC LearnC++ LearnC# LearnR LearnKotlin LearnGo LearnDjango LearnTypeScript ServerSide LearnSQL LearnMySQL LearnPHP LearnASP LearnNode.js LearnRaspberryPi LearnGit LearnAWSCloud WebBuilding CreateaWebsiteNEW WhereToStart WebTemplates WebStatistics WebCertificates WebDevelopment CodeEditor TestYourTypingSpeed PlayaCodeGame CyberSecurity Accessibility DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel LearnGoogleSheets XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery × References HTML HTMLTagReference HTMLBrowserSupport HTMLEventReference HTMLColorReference HTMLAttributeReference HTMLCanvasReference HTMLSVGReference GoogleMapsReference CSS CSSReference CSSBrowserSupport CSSSelectorReference Bootstrap3Reference Bootstrap4Reference W3.CSSReference IconReference SassReference JavaScript JavaScriptReference HTMLDOMReference jQueryReference AngularJSReference AppMLReference W3.JSReference Programming PythonReference JavaReference ServerSide SQLReference MySQLReference PHPReference ASPReference XML XMLDOMReference XMLHttpReference XSLTReference XMLSchemaReference CharacterSets HTMLCharacterSets HTMLASCII HTMLANSI HTMLWindows-1252 HTMLISO-8859-1 HTMLSymbols HTMLUTF-8 × ExercisesandQuizzes Exercises HTMLExercises CSSExercises JavaScriptExercises SQLExercises MySQLExercises PHPExercises PythonExercises NumPyExercises PandasExercises SciPyExercises jQueryExercises JavaExercises C++Exercises C#Exercises RExercises KotlinExercises GoExercises BootstrapExercises Bootstrap4Exercises Bootstrap5Exercises GitExercises Quizzes HTMLQuiz CSSQuiz JavaScriptQuiz SQLQuiz MySQLQuiz PHPQuiz PythonQuiz NumPyQuiz PandasQuiz SciPyQuiz jQueryQuiz JavaQuiz C++Quiz C#Quiz RQuiz KotlinQuiz XMLQuiz BootstrapQuiz Bootstrap4Quiz Bootstrap5Quiz CyberSecurityQuiz AccessibilityQuiz Courses HTMLCourse CSSCourse JavaScriptCourse FrontEndCourse SQLCourse PHPCourse PythonCourse NumPyCourse PandasCourse DataAnalyticsCourse jQueryCourse JavaCourse C++Course C#Course RCourse XMLCourse CyberSecurityCourse AccessibilityCourse Certificates HTMLCertificate CSSCertificate JavaScriptCertificate FrontEndCertificate SQLCertificate PHPCertificate PythonCertificate DataScienceCertificate Bootstrap3Certificate Bootstrap4Certificate jQueryCertificate JavaCertificate C++Certificate ReactCertificate XMLCertificate × Tutorials References Exercises PaidCourses Spaces Videos Shop Pro JSTutorial JSHOME JSIntroduction JSWhereTo JSOutput JSStatements JSSyntax JSComments JSVariables JSLet JSConst JSOperators JSArithmetic JSAssignment JSDataTypes JSFunctions JSObjects JSEvents JSStrings JSStringMethods JSStringSearch JSStringTemplates JSNumbers JSNumberMethods JSArrays JSArrayMethods JSArraySort JSArrayIteration JSArrayConst JSDates JSDateFormats JSDateGetMethods JSDateSetMethods JSMath JSRandom JSBooleans JSComparisons JSIfElse JSSwitch JSLoopFor JSLoopForIn JSLoopForOf JSLoopWhile JSBreak JSIterables JSSets JSMaps JSTypeof JSTypeConversion JSBitwise JSRegExp JSErrors JSScope JSHoisting JSStrictMode JSthisKeyword JSArrowFunction JSClasses JSModules JSJSON JSDebugging JSStyleGuide JSBestPractices JSMistakes JSPerformance JSReservedWords JSVersions JSVersions JS2009(ES5) JS2015(ES6) JS2016 JS2017 JS2018 JSIE/Edge JSHistory JSObjects ObjectDefinitions ObjectProperties ObjectMethods ObjectDisplay ObjectAccessors ObjectConstructors ObjectPrototypes ObjectIterables ObjectSets ObjectMaps ObjectReference JSFunctions FunctionDefinitions FunctionParameters FunctionInvocation FunctionCall FunctionApply FunctionBind FunctionClosures JSClasses ClassIntro ClassInheritance ClassStatic JSAsync JSCallbacks JSAsynchronous JSPromises JSAsync/Await JSHTMLDOM DOMIntro DOMMethods DOMDocument DOMElements DOMHTML DOMForms DOMCSS DOMAnimations DOMEvents DOMEventListener DOMNavigation DOMNodes DOMCollections DOMNodeLists JSBrowserBOM JSWindow JSScreen JSLocation JSHistory JSNavigator JSPopupAlert JSTiming JSCookies JSWebAPIs WebAPIIntro WebFormsAPI WebHistoryAPI WebStorageAPI WebWorkerAPI WebFetchAPI WebGeolocationAPI JSAJAX AJAXIntro AJAXXMLHttp AJAXRequest AJAXResponse AJAXXMLFile AJAXPHP AJAXASP AJAXDatabase AJAXApplications AJAXExamples JSJSON JSONIntro JSONSyntax JSONvsXML JSONDataTypes JSONParse JSONStringify JSONObjects JSONArrays JSONServer JSONPHP JSONHTML JSONJSONP JSvsjQuery jQuerySelectors jQueryHTML jQueryCSS jQueryDOM JSGraphics JSGraphics JSCanvas JSPlotly JSChart.js JSGoogleChart JSD3.js JSExamples JSExamples JSHTMLDOM JSHTMLInput JSHTMLObjects JSHTMLEvents JSBrowser JSEditor JSExercises JSQuiz JSCertificate JSReferences JavaScriptObjects HTMLDOMObjects JavaScriptComparisonandLogicalOperators ❮Previous Next❯ ComparisonandLogicaloperatorsareusedtotestfortrueor false. ComparisonOperators Comparisonoperatorsareusedinlogicalstatementstodetermineequalityordifferencebetweenvariablesorvalues. Giventhatx=5,thetablebelowexplainsthecomparisonoperators: Operator Description Comparing Returns Tryit == equalto x==8 false Tryit» x==5 true Tryit» x=="5" true Tryit» === equalvalueandequaltype x===5 true Tryit» x==="5" false Tryit» != notequal x!=8 true Tryit» !== notequalvalueornotequaltype x!==5 false Tryit» x!=="5" true Tryit» x!==8 true Tryit» > greaterthan x>8 false Tryit» < lessthan x<8 true Tryit» >= greaterthanorequalto x>=8 false Tryit» <= lessthanorequalto x<=8 true Tryit» HowCanitbeUsed Comparisonoperatorscanbeusedinconditionalstatementstocomparevalues andtakeactiondependingontheresult: if(age<18)text="Tooyoungtobuyalcohol"; Youwilllearnmoreabouttheuseofconditionalstatementsinthenextchapterofthistutorial. LogicalOperators Logicaloperatorsareusedtodeterminethelogicbetweenvariablesorvalues. Giventhatx=6andy=3,thetablebelowexplainsthelogicaloperators: Operator Description Example Tryit && and (x<10&&y>1)istrue Tryit» || or (x==5||y==5)isfalse Tryit» ! not !(x==y)istrue Tryit» Conditional(Ternary)Operator JavaScriptalsocontainsaconditionaloperatorthatassignsavaluetoavariablebasedonsomecondition. Syntax variablename=(condition)?value1:value2 Example letvoteable=(age<18)?"Tooyoung":"Oldenough"; TryitYourself» Ifthevariableageisavaluebelow18,thevalueofthevariablevoteable willbe"Tooyoung",otherwisethevalueofvoteablewillbe"Oldenough". ComparingDifferentTypes Comparingdataofdifferenttypesmaygiveunexpectedresults. Whencomparingastringwithanumber,JavaScriptwillconvertthestringto anumberwhendoingthecomparison.Anemptystringconvertsto0.Anon-numeric stringconvertstoNaNwhichisalwaysfalse. Case Value Try 2<12 true Tryit» 2"John" false Tryit» 2=="John" false Tryit» "2""12" true Tryit» "2"=="12" false Tryit» Whencomparingtwostrings,"2"willbegreaterthan"12",because (alphabetically)1islessthan2. Tosecureaproperresult,variablesshouldbeconvertedtothepropertype beforecomparison: age=Number(age); if(isNaN(age)){ voteable="Inputisnotanumber"; }else{ voteable=(age<18)?"Tooyoung":"Oldenough"; } TryitYourself» TestYourselfWithExercises Exercise: Choosethecorrectcomparisonoperatortoalerttrue,whenxisgreaterthany. x=10; y=5; alert(xy); SubmitAnswer» StarttheExercise» ❮Previous Next❯ NEW WejustlaunchedW3Schoolsvideos Explorenow COLORPICKER Getcertifiedbycompletingacoursetoday! w3schoolsCERTIFIED.2022 Getstarted CODEGAME PlayGame
延伸文章資訊
- 1JavaScript 基礎知識-邏輯運算子&&,|| - iT 邦幫忙
JavaScript 基礎知識-邏輯運算子&&,|| ... 生活上也會有類似的邏輯判斷,例如:媽媽拜託小明去市場買菜,要買到牛肉,青菜和洋蔥,成功買到這三樣,媽媽才 ...
- 2運算式與運算子- JavaScript
在JavaScript 中基本的關鍵字與一般的運算式。 this: this 關鍵字可以參考執行函數的所在位置。 function (en-US): function 關鍵字可以定義一個函數 ...
- 3JavaScript 邏輯運算&& ( and )、| | ( or )、!( not )
- 4JavaScript Operators - W3Schools
Assignment operators are fully described in the JS Assignment chapter. JavaScript String Operator...
- 5CSS, Bootstrap And JavaScript And Python Stack Course
What you'll learn · Introduction to Web development with learning CSS And Bootstrap JavaScript co...