CINXE.COM

<!DOCTYPE html><html lang="id" data-theme-enabled="1"><head><script>window.currentUser = null;</script><script>window.shopCurrency = "EUR";</script><script>window.localCurrency = "EUR";</script><script>window.countryCode = "sg";</script><script>window.rateShopTo = {"EUR":1,"USD":1.0914313904399342,"AMD":426.6372442230537};</script><title itemprop="name">Eval: menjalankan kode dari _string_</title><link href="/pack/styles.100020a0bc7cf13be729.css" rel="stylesheet"><meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes, minimum-scale=1.0"><meta name="apple-mobile-web-app-capable" content="yes"><!-- chrome autotranslate is enabled only for "en" main version--><meta name="google" content="notranslate"><script>if (window.devicePixelRatio > 1) document.cookie = 'pixelRatio=' + window.devicePixelRatio + ';path=/;expires=Tue, 19 Jan 2038 03:14:07 GMT';</script><link href="//fonts.googleapis.com/css?family=Open+Sans:bold,italic,bolditalic" rel="stylesheet"><link rel="apple-touch-icon-precomposed" href="/img/favicon/apple-touch-icon-precomposed.png"><link rel="canonical" href="https://id.javascript.info/eval"><meta name="msapplication-TileColor" content="#222A2C"><meta name="msapplication-TileImage" content="/img/favicon/tileicon.png"><link rel="icon" href="/img/favicon/favicon.png"><meta itemprop="image" content="https://id.javascript.info/img/site_preview_en_512x512.png"><meta property="og:title" content="Eval: menjalankan kode dari _string_"><meta property="og:image" content="https://id.javascript.info/img/site_preview_en_1200x630.png"><meta property="og:image:type" content="image/png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630"><meta property="fb:admins" content="100001562528165"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="Eval: menjalankan kode dari _string_"><meta name="twitter:site" content="@iliakan"><meta name="twitter:creator" content="@iliakan"><meta name="twitter:image" content="https://id.javascript.info/img/site_preview_en_512x512.png"><meta name="google-adsense-account" content="ca-pub-6204518652652613"><link rel="prev" href="/proxy"><link rel="next" href="/currying-partials"><script data-collect-dnt="true" async src="https://scripts.simpleanalyticscdn.com/latest.js"></script><script>window.GA_ID = "UA-2056213-15";</script><script>window.YANDEX_METRIKA_ID = 32184394;</script><script>{function gtag(){dataLayer.push(arguments)}window.dataLayer=window.dataLayer||[],gtag("js",new Date),gtag("config","G-2LWB61WGYJ")}</script> <script async src="https://www.googletagmanager.com/gtag/js?id=G-2LWB61WGYJ"></script><script>window.metrika={reachGoal:function(){}},window.yandex_metrika_callbacks=[function(){try{window.metrika=new Ya.Metrika({id:YANDEX_METRIKA_ID,webvisor:!0,clickmap:!0,params:{user:window.currentUser&&window.currentUser.id}}),metrika.trackLinks({delay:150}),window.addEventListener("error",function(r){window.metrika.reachGoal("JSERROR",{src:(r.filename||r.errorUrl)+": "+(r.lineno||r.errorLine),stack:r.stack||r.error&&r.error.stack,message:r.message})})}catch(r){}}];</script><script src="//mc.yandex.ru/metrika/watch.js" async></script><script>window.RECAPTCHA_ID = "6LfmLAEVAAAAAJMykMnf7aY8nkyTRmYi2ynx51R1";</script><script src="/pack/init.8e317947739199dfffcc.js"></script><script src="/pack/head.2a9ffab40f5a633784ee.js" defer></script><meta property="og:title" content="Eval: menjalankan kode dari _string_"><meta property="og:type" content="article"><script src="/pack/tutorial.c00bd856dcc07c4cfeb3.js" defer></script><script src="/pack/footer.497c7465415a38fca9ce.js" defer></script></head><body class="no-icons"><script>window.fontTest();</script><div class="page-wrapper page-wrapper_sidebar_on"><!--[if IE]><div style="color:red;text-align:center">Maaf, Internet Explorer tidak didukung, harap gunakan browser yang lebih baru.</div><![endif]--><div class="sitetoolbar sitetoolbar_tutorial"><script>window.langs = [{"code":"ar","name":"Arabic"},{"code":"az","name":"Azerbaijani"},{"code":"bg","name":"Bulgarian"},{"code":"bn","name":"Bengali"},{"code":"bs","name":"Bosnian"},{"code":"ca","name":"Catalan"},{"code":"cs","name":"Czech"},{"code":"da","name":"Danish"},{"code":"de","name":"German"},{"code":"el","name":"Greek"},{"code":"en","name":"English"},{"code":"es","name":"Spanish"},{"code":"fa","name":"Persian (Farsi)"},{"code":"fi","name":"Finnish"},{"code":"fr","name":"French"},{"code":"he","name":"Hebrew"},{"code":"hi","name":"Hindi"},{"code":"hr","name":"Croatian"},{"code":"hu","name":"Hungarian"},{"code":"hy","name":"Armenian"},{"code":"id","name":"Indonesian"},{"code":"it","name":"Italian"},{"code":"ja","name":"Japanese"},{"code":"ka","name":"Georgian"},{"code":"kk","name":"Kazakh"},{"code":"km","name":"Central Khmer"},{"code":"ko","name":"Korean"},{"code":"ku","name":"Kurdish"},{"code":"ky","name":"Kyrgyz"},{"code":"lt","name":"Lithuanian"},{"code":"me","name":"Montenegrin"},{"code":"ml","name":"Malayalam"},{"code":"ms","name":"Malay"},{"code":"my","name":"Burmese"},{"code":"nl","name":"Dutch"},{"code":"no","name":"Norvegian"},{"code":"pa","name":"Punjabi"},{"code":"pl","name":"Polish"},{"code":"pt","name":"Portuguese"},{"code":"ro","name":"Romanian"},{"code":"ru","name":"Russian"},{"code":"si","name":"Sinhala"},{"code":"sk","name":"Slovak"},{"code":"sl","name":"Slovenian"},{"code":"sq","name":"Albanian"},{"code":"sr","name":"Serbian"},{"code":"ta","name":"Tamil"},{"code":"te","name":"Telugu"},{"code":"test","name":"Test"},{"code":"th","name":"Thai"},{"code":"tk","name":"Turkmen"},{"code":"tr","name":"Turkish"},{"code":"ug","name":"Uyghur"},{"code":"uk","name":"Ukrainian"},{"code":"ur","name":"Urdu"},{"code":"uz","name":"Uzbek"},{"code":"v2","name":"v2"},{"code":"vi","name":"Vietnamese"},{"code":"zh-hant","name":"Chinese Traditional"},{"code":"zh","name":"Chinese"}];</script><script>window.lang = "id";</script><div class="sitetoolbar__content"><div class="sitetoolbar__lang-switcher"><button class="sitetoolbar__dropdown-button" data-dropdown-toggler>ID</button><div class="sitetoolbar__dropdown-wrap"><div class="sitetoolbar__dropdown-body"><div class="sitetoolbar__lang-switcher-body"><div class="supported-langs supported-langs_toolbar"><div class="supported-langs__container"><ul class="supported-langs__list" style="height:200px"><li class="supported-langs__item"><a class="supported-langs__link" href="https://ar.javascript.info/eval"><span class="supported-langs__brief">AR</span><span class="supported-langs__title">عربي</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://javascript.info/eval"><span class="supported-langs__brief">EN</span><span class="supported-langs__title">English</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://es.javascript.info/eval"><span class="supported-langs__brief">ES</span><span class="supported-langs__title">Español</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://fa.javascript.info/eval"><span class="supported-langs__brief">FA</span><span class="supported-langs__title">فارسی</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://fr.javascript.info/eval"><span class="supported-langs__brief">FR</span><span class="supported-langs__title">Français</span></a></li><li class="supported-langs__item supported-langs__item_current"><a class="supported-langs__link" href="https://id.javascript.info/eval"><span class="supported-langs__brief">ID</span><span class="supported-langs__title">Indonesia</span></a></li></ul><ul class="supported-langs__list" style="height:200px"><li class="supported-langs__item"><a class="supported-langs__link" href="https://it.javascript.info/eval"><span class="supported-langs__brief">IT</span><span class="supported-langs__title">Italiano</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://ja.javascript.info/eval"><span class="supported-langs__brief">JA</span><span class="supported-langs__title">日本語</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://ko.javascript.info/eval"><span class="supported-langs__brief">KO</span><span class="supported-langs__title">한국어</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://learn.javascript.ru/eval"><span class="supported-langs__brief">RU</span><span class="supported-langs__title">Русский</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://tr.javascript.info/eval"><span class="supported-langs__brief">TR</span><span class="supported-langs__title">Türkçe</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://uk.javascript.info/eval"><span class="supported-langs__brief">UK</span><span class="supported-langs__title">Українська</span></a></li></ul><ul class="supported-langs__list" style="height:20px"><li class="supported-langs__item"><a class="supported-langs__link" href="https://zh.javascript.info/eval"><span class="supported-langs__brief">ZH</span><span class="supported-langs__title">简体中文</span></a></li></ul></div><div class="supported-langs__text"><p>Kami ingin membuat proyek open source ini tersedia untuk orang-orang di seluruh dunia.</p> <p><a href="https://javascript.info/translate">Bantu untuk menerjemahkan</a> konten tutorial ini ke bahasa Anda!</p> </div></div></div></div></div></div><div class="sitetoolbar__logo-wrap"><a class="sitetoolbar__link sitetoolbar__link_logo" href="/"><img class="sitetoolbar__logo sitetoolbar__logo_normal" src="/img/sitetoolbar__logo_en.svg" width="200" alt="" role="presentation"/><img class="sitetoolbar__logo sitetoolbar__logo_normal sitetoolbar__logo_dark" src="/img/sitetoolbar__logo_en-white.svg" width="200" alt="" role="presentation"/><img class="sitetoolbar__logo sitetoolbar__logo_small" src="/img/sitetoolbar__logo_small_en.svg" width="70" alt="" role="presentation"/><img class="sitetoolbar__logo sitetoolbar__logo_small sitetoolbar__logo_dark" src="/img/sitetoolbar__logo_small_en-white.svg" width="70" alt="" role="presentation"/><script>Array.prototype.forEach.call(document.querySelectorAll("img.sitetoolbar__logo"),function(e){let t=document.createElement("object");t.type="image/svg+xml",t.className=e.className,t.style.cssText="left:0;top:0;position:absolute",t.onload=function(){t.onload=null,e.style.visibility="hidden"},t.data=e.src,e.parentNode.insertBefore(t,e)});</script></a></div><div class="sitetoolbar__nav-toggle-wrap"><button class="sitetoolbar__nav-toggle" type="button"></button></div><nav class="sitetoolbar__sections"><ul class="sitetoolbar__sections-list"></ul></nav><div class="sitetoolbar__theme-switcher"><div class="theme-changer"><label class="theme-changer__label" for="theme-changer-input" data-tooltip="Change theme"><input class="theme-changer__input" type="checkbox" id="theme-changer-input" data-theme-changer="data-theme-changer"/><span class="theme-changer__icon theme-changer__icon_light-theme"></span><span class="theme-changer__icon theme-changer__icon_dark-theme"></span></label></div></div><div class="sitetoolbar__search-wrap"><div class="sitetoolbar__search-content"><button class="sitetoolbar__search-toggle" type="button"></button><form class="sitetoolbar__search" method="GET" action="/search"><div class="sitetoolbar__search-input"><div class="text-input"><input class="text-input__control" name="query" placeholder="Cari pada Javascript.info" required="required" type="text"/></div><button class="sitetoolbar__find" type="submit">Cari</button></div></form></div></div></div><div class="tablet-menu"><div class="tablet-menu__line"><div class="tablet-menu__content"><form class="tablet-menu-search" action="/search/"><input class="tablet-menu-search__input" type="search" name="query" placeholder="Cari di tutorial" required="required"/><button class="tablet-menu-search__button" type="submit" name="type" value="articles">Cari</button></form></div></div><div class="tablet-menu__line"><div class="tablet-menu__content"><a class="map" href="/tutorial/map" data-action="tutorial-map"><span class="map__text">Peta tutorial</span></a></div></div><div class="tablet-menu__line"><div class="tablet-menu__content"><div class="theme-changer theme-changer_tablet-menu theme-changer_has-label"><label class="theme-changer__label" for="theme-changer-input-tablet" data-tooltip="Change theme"><input class="theme-changer__input" type="checkbox" id="theme-changer-input-tablet" data-theme-changer="data-theme-changer"/><span class="theme-changer__icon theme-changer__icon_light-theme"></span><span class="theme-changer__icon theme-changer__icon_dark-theme"></span><span class="theme-changer__label-text theme-changer__label-text_light-theme">Light theme</span><span class="theme-changer__label-text theme-changer__label-text_dark-theme">Dark theme</span></label></div></div></div><div class="tablet-menu__line"><div class="tablet-menu__content"><div class="share-icons"><span class="share-icons__title">Bagikan</span><a class="share share_tw" href="https://twitter.com/share?url=https%3A%2F%2Fid.javascript.info%2Feval" rel="nofollow"></a><a class="share share_fb" href="https://www.facebook.com/sharer/sharer.php?s=100&amp;p%5Burl%5D=https%3A%2F%2Fid.javascript.info%2Feval" rel="nofollow"></a></div></div></div><div class="tablet-menu__line"><div class="tablet-menu__content"><select class="tablet-menu__nav input-select input-select input-select_small" onchange="if(this.value) window.location.href=this.value"><option value="https://ar.javascript.info/eval">عربي</option><option value="https://javascript.info/eval">English</option><option value="https://es.javascript.info/eval">Español</option><option value="https://fa.javascript.info/eval">فارسی</option><option value="https://fr.javascript.info/eval">Français</option><option value="https://id.javascript.info/eval" selected>Indonesia</option><option value="https://it.javascript.info/eval">Italiano</option><option value="https://ja.javascript.info/eval">日本語</option><option value="https://ko.javascript.info/eval">한국어</option><option value="https://learn.javascript.ru/eval">Русский</option><option value="https://tr.javascript.info/eval">Türkçe</option><option value="https://uk.javascript.info/eval">Українська</option><option value="https://zh.javascript.info/eval">简体中文</option></select></div></div></div><progress class="tutorial-progress" data-sticky value="89" max="92" data-tooltip="Pelajaran 89 dari 92"></progress></div><div class="page page_sidebar_on page_inner_padding"><script>if(localStorage.noSidebar){document.querySelector(".page").classList.remove("page_sidebar_on");let e=document.querySelector(".page-wrapper");e&&e.classList.remove("page-wrapper_sidebar_on")}setTimeout(function(){document.querySelector(".page").classList.add("page_sidebar-animation-on")});</script><div class="page__inner"><main class="main main_width-limit"><header class="main__header"><div class="main__header-inner"><div class="main__header-group"><ol class="breadcrumbs"><li class="breadcrumbs__item breadcrumbs__item_home"><a class="breadcrumbs__link" href="/"><span class="breadcrumbs__hidden-text">Tutorial</span></a></li><li class="breadcrumbs__item" id="breadcrumb-1"><a class="breadcrumbs__link" href="/js"><span>Bahasa JavaScript</span></a></li><li class="breadcrumbs__item" id="breadcrumb-2"><a class="breadcrumbs__link" href="/js-misc"><span>Miscellaneous</span></a></li><script type="application/ld+json">{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Tutorial","item":"https://id.javascript.info/"},{"@type":"ListItem","position":2,"name":"Bahasa JavaScript","item":"https://id.javascript.info/js"},{"@type":"ListItem","position":3,"name":"Miscellaneous","item":"https://id.javascript.info/js-misc"}]}</script></ol><div class="updated-at" data-tooltip="Terakhir diperbarui pada 7 Oktober 2020"><div class="updated-at__content">7 Oktober 2020</div></div></div><h1 class="main__header-title">Eval: menjalankan kode dari _string_</h1></div></header><div class="content"><article class="formatted" itemscope itemtype="http://schema.org/TechArticle"><meta itemprop="name" content="Eval: menjalankan kode dari _string_"><div itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="email" content="iliakan@gmail.com"><meta itemprop="name" content="Ilya Kantor"></div><div itemprop="articleBody"><p>Fungsi bawaan <code>eval</code> memungkinkan kita untuk menjalankan kode dari sebuah <em>string</em>.</p> <p>Sintaksnya adalah:</p> <div id="tfjyx6pp81" data-trusted="1" class="code-example"> <div class="codebox code-example__codebox"> <div class="codebox__code" data-code="1"> <pre class="line-numbers language-javascript"><code>let result = eval(code);</code></pre> </div> </div> </div><p>Sebagai contoh:</p> <div id="8ewzqcs5nr" data-trusted="1" class="code-example"> <div class="codebox code-example__codebox"> <div class="toolbar codebox__toolbar"> <div class="toolbar__tool"> <a href="#" title="jalankan" data-action="run" class="toolbar__button toolbar__button_run"></a> </div> <div class="toolbar__tool"> <a href="#" title="buka pada sandbox" target="_blank" data-action="edit" class="toolbar__button toolbar__button_edit"></a> </div> </div> <div class="codebox__code" data-code="1"> <pre class="line-numbers language-javascript"><code>let code = 'alert(&quot;Halo&quot;)'; eval(code); // Halo</code></pre> </div> </div> </div><p>Sebuah kode yang berupa <em>string</em> bisa panjang, berupa deklarasi fungsi, variabel dan lain-lain.</p> <p>Hasil dari <code>eval</code> adalah hasil dari peryataan terakhir.</p> <p>Sebagai contoh:</p> <div id="uf3aysjeji" data-trusted="1" class="code-example"> <div class="codebox code-example__codebox"> <div class="toolbar codebox__toolbar"> <div class="toolbar__tool"> <a href="#" title="jalankan" data-action="run" class="toolbar__button toolbar__button_run"></a> </div> <div class="toolbar__tool"> <a href="#" title="buka pada sandbox" target="_blank" data-action="edit" class="toolbar__button toolbar__button_edit"></a> </div> </div> <div class="codebox__code" data-code="1"> <pre class="line-numbers language-javascript"><code>let value = eval('1+1'); alert(value); // 2</code></pre> </div> </div> </div><div id="em3ai83zvk" data-trusted="1" class="code-example"> <div class="codebox code-example__codebox"> <div class="toolbar codebox__toolbar"> <div class="toolbar__tool"> <a href="#" title="jalankan" data-action="run" class="toolbar__button toolbar__button_run"></a> </div> <div class="toolbar__tool"> <a href="#" title="buka pada sandbox" target="_blank" data-action="edit" class="toolbar__button toolbar__button_edit"></a> </div> </div> <div class="codebox__code" data-code="1"> <pre class="line-numbers language-javascript"><code>let value = eval('let i = 0; ++i'); alert(value); // 1</code></pre> </div> </div> </div><p>Kode yang dievaluasi akan dieksekusi di lingkungan leksikal saat ini, sehingga dapat melihat variabel luar:</p> <div id="u6sj2siir1" data-trusted="1" class="code-example" data-highlight="[{&quot;start&quot;:5,&quot;end&quot;:5}]"> <div class="codebox code-example__codebox"> <div class="toolbar codebox__toolbar"> <div class="toolbar__tool"> <a href="#" title="jalankan" data-action="run" class="toolbar__button toolbar__button_run"></a> </div> <div class="toolbar__tool"> <a href="#" title="buka pada sandbox" target="_blank" data-action="edit" class="toolbar__button toolbar__button_edit"></a> </div> </div> <div class="codebox__code" data-code="1"> <pre class="line-numbers language-javascript"><code>let a = 1; function f() { let a = 2; eval('alert(a)'); // 2 } f();</code></pre> </div> </div> </div><p>Itu juga dapat mengubah variabel luar:</p> <div id="8l2gom2u61" data-trusted="0" class="code-example" data-refresh="1"> <div class="codebox code-example__codebox"> <div class="toolbar codebox__toolbar"> <div class="toolbar__tool"> <a href="#" title="jalankan" data-action="run" class="toolbar__button toolbar__button_run"></a> </div> <div class="toolbar__tool"> <a href="#" title="buka pada sandbox" target="_blank" data-action="edit" class="toolbar__button toolbar__button_edit"></a> </div> </div> <div class="codebox__code" data-code="1"> <pre class="line-numbers language-javascript"><code>let x = 5; eval(&quot;x = 10&quot;); alert(x); // 10, nilai diubah</code></pre> </div> </div> </div><p>Dalam mode ketat, <code>eval</code> memiliki lingkungan leksikal sendiri. Jadi, fungsi dan variabel yang dideklarasikan di dalam eval, tidak akan terlihat di luar:</p> <div id="d44sh1a310" data-trusted="0" class="code-example" data-refresh="1"> <div class="codebox code-example__codebox"> <div class="toolbar codebox__toolbar"> <div class="toolbar__tool"> <a href="#" title="jalankan" data-action="run" class="toolbar__button toolbar__button_run"></a> </div> <div class="toolbar__tool"> <a href="#" title="buka pada sandbox" target="_blank" data-action="edit" class="toolbar__button toolbar__button_edit"></a> </div> </div> <div class="codebox__code" data-code="1"> <pre class="line-numbers language-javascript"><code>// pengingat: dalam contoh yang dijalankan 'use strict' diaktifkan secara bawaan eval(&quot;let x = 5; function f() {}&quot;); alert(typeof x); // undefined (tidak ada variabel) // fungsi f juga tidak terlihat</code></pre> </div> </div> </div><p>Tanpa <code>use strict</code>, <code>eval</code> tidak memiliki lingkungan leksikal sendiri, jadi kita akan melihat <code>x</code> dan <code>f</code> di luar.</p> <h2><a class="main__anchor" name="menggunakan-eval" href="#menggunakan-eval">Menggunakan “eval”</a></h2><p>Dalam pemrograman modern <code>eval</code> jarang digunakan. Sering dikatakan bahwa “<em>eval is evil</em>” atau “<code>eval</code> itu jahat”.</p> <p>Alasannya sederhana: dulu JavaScript adalah bahasa yang jauh lebih lemah, banyak hal yang hanya bisa dilakukan dengan <code>eval</code>. Tapi waktu itu telah berlalu satu dekade yang lalu.</p> <p>Sekarang, hampir tidak ada alasan untuk menggunakan <code>eval</code>. Jika seseorang menggunakannya, ada kemungkinan mereka dapat menggantinya dengan konstruksi bahasa modern atau <a href="/modules">JavaScript Module</a>.</p> <p>Harap dicatat bahwa kemampuannya untuk mengakses variabel luar memiliki efek samping.</p> <p><em>Code minifiers</em> (alat yang digunakan sebelum JS masuk ke produksi, untuk mengkompresnya) mengubah nama variabel lokal menjadi lebih pendek (seperti <code>a</code>, <code>b</code> dll) untuk membuat kode menjadi lebih kecil. Biasanya itu aman, tetapi tidak jika <code>eval</code> digunakan, karena variabel lokal dapat diakses dari kode yang dievaluasi dari <em>string</em>. Jadi <em>minifiers</em> tidak melakukan itu untuk mengganti nama semua variabel yang terlihat dari <code>eval</code>. Itu berdampak negatif pada rasio kompresi kode.</p> <p>Menggunakan variabel lokal luar di dalam <code>eval</code> juga dianggap sebagai praktik pemrograman yang buruk, karena membuat kode lebih sulit dipertahankan.</p> <p>Ada dua cara untuk terhindar dan aman dari masalah seperti itu.</p> <p><strong>Jika kode yang dievaluasi tidak menggunakan variabel luar, panggil <code>eval</code> sebagai <code>window.eval(...)</code>:</strong></p> <p>Dengan cara ini, kode akan dijalankan dalam lingkup global:</p> <div id="0ak4ieml4f" data-trusted="0" class="code-example" data-refresh="1"> <div class="codebox code-example__codebox"> <div class="toolbar codebox__toolbar"> <div class="toolbar__tool"> <a href="#" title="jalankan" data-action="run" class="toolbar__button toolbar__button_run"></a> </div> <div class="toolbar__tool"> <a href="#" title="buka pada sandbox" target="_blank" data-action="edit" class="toolbar__button toolbar__button_edit"></a> </div> </div> <div class="codebox__code" data-code="1"> <pre class="line-numbers language-javascript"><code>let x = 1; { let x = 5; window.eval('alert(x)'); // 1 (variabel global) }</code></pre> </div> </div> </div><p><strong>Jika kode yang dievaluasi membutuhkan variabel lokal, ubah <code>eval</code> menjadi <code>new Function</code> dan teruskan sebagai argumen:</strong></p> <div id="nm97c92tqi" data-trusted="1" class="code-example"> <div class="codebox code-example__codebox"> <div class="toolbar codebox__toolbar"> <div class="toolbar__tool"> <a href="#" title="jalankan" data-action="run" class="toolbar__button toolbar__button_run"></a> </div> <div class="toolbar__tool"> <a href="#" title="buka pada sandbox" target="_blank" data-action="edit" class="toolbar__button toolbar__button_edit"></a> </div> </div> <div class="codebox__code" data-code="1"> <pre class="line-numbers language-javascript"><code>let f = new Function('a', 'alert(a)'); f(5); // 5</code></pre> </div> </div> </div><p>Konstruksi <code>new Function</code> dijelaskan dalam bab <a href="/new-function">Sintaks &quot;new Function&quot;</a>. Itu membuat fungsi baru dari sebuah <em>string</em> dan juga dalam lingkup global. Jadi tidak bisa melihat variabel lokal. Tetapi jauh lebih jelas jika meneruskannya sebagai argumen secara eksplisit, seperti pada contoh di atas.</p> <h2><a class="main__anchor" name="ringkasan" href="#ringkasan">Ringkasan</a></h2><p>Pemanggilan <code>eval(code)</code> menjalankan kode dari sebuah <em>string</em> dan mengembalikan hasil dari pernyataan terakhir.</p> <ul> <li>Jarang digunakan dalam JavaScript modern, karena biasanya tidak diperlukan.</li> <li>Dapat mengakses variabel lokal luar. Itu dianggap praktik yang buruk.</li> <li>Sebaga gantinya, untuk <code>eval</code> sebuah kode dalam lingkup global, gunakan <code>window.eval(code)</code>.</li> <li>Atau, jika kode Anda memerlukan beberapa data dari cakupan luar, gunakan <code>new Function</code> dan teruskan sebagai argumen.</li> </ul> </div></article><div class="tasks formatted"><h2 class="tasks__title" id="tasks"><a class="tasks__title-anchor main__anchor main__anchor main__anchor_noicon" href="#tasks">Tugas</a></h2><div class="task tasks__task"><div class="task__header"><div class="task__title-wrap"><h3 class="task__title"><a class="main__anchor" href="#kalkulator-eval" name="kalkulator-eval">Kalkulator-_eval_</a></h3><a class="task__open-link" href="/task/eval-calculator" target="_blank"></a></div><div class="task__header-note"><span class="task__importance" title="Seberapa penting tugas itu, dari 1 hingga 5">pentingnya: 4</span></div><div class="task__content"><div class="task__formatted"><p>Buatlah kalkulator yang meminta operasi aritmatika dan mengembalikan hasilnya.</p> <p>Tidak perlu memeriksa kebenaran operasi dalam tugas ini. Cukup evaluasi dan kembalikan hasilnya.</p> <p><a href="#" onclick="event.preventDefault(); runDemo(this)">jalankan demonya</a></p></div><button class="task__solution" type="button">solusi</button><div class="task__answer"><div class="task__answer-content"><div class="formatted"><p>Mari gunakan <code>eval</code> untuk menghitung rumus matematika:</p> <div id="i9g1m4hjhq" data-trusted="1" class="code-example" data-demo="1"> <div class="codebox code-example__codebox"> <div class="toolbar codebox__toolbar"> <div class="toolbar__tool"> <a href="#" title="jalankan" data-action="run" class="toolbar__button toolbar__button_run"></a> </div> <div class="toolbar__tool"> <a href="#" title="buka pada sandbox" target="_blank" data-action="edit" class="toolbar__button toolbar__button_edit"></a> </div> </div> <div class="codebox__code" data-code="1"> <pre class="line-numbers language-javascript"><code>let expr = prompt(&quot;Type an arithmetic expression?&quot;, '2*3+2'); alert( eval(expr) );</code></pre> </div> </div> </div><p>Pengguna dapat memasukkan teks atau kode apa pun.</p> <p>Untuk membuat semuanya aman dan membatasinya hanya untuk operasi aritmatika, kita dapat memeriksa <code>expr</code> menggunakan <a href="/regular-expressions"><em>regular expression</em></a>, sehingga hanya dapat berisi angka dan operator.</p> </div></div><button class="close-button task__answer-close" type="button" title="tutup"></button></div></div></div></div></div></div><div class="page__nav-wrap"><a class="page__nav page__nav_prev" href="/proxy" data-tooltip="Proxy and Reflect"><span class="page__nav-text"><span class="page__nav-text-shortcut"></span></span><span class="page__nav-text-alternate">Pelajaran sebelumnya</span></a><a class="page__nav page__nav_next" href="/currying-partials" data-tooltip="_Currying_"><span class="page__nav-text"><span class="page__nav-text-shortcut"></span></span><span class="page__nav-text-alternate">Pelajaran berikutnya</span></a></div><div class="article-tablet-foot tablet-only"><div class="article-tablet-foot__layout"><div class="share-icons"><span class="share-icons__title">Bagikan</span><a class="share share_tw" href="https://twitter.com/share?url=https%3A%2F%2Fid.javascript.info%2Feval" rel="nofollow"></a><a class="share share_fb" href="https://www.facebook.com/sharer/sharer.php?s=100&amp;p%5Burl%5D=https%3A%2F%2Fid.javascript.info%2Feval" rel="nofollow"></a></div><div class="article-tablet-foot__map"><a class="map" href="/tutorial/map" data-action="tutorial-map"><span class="map__text">Peta tutorial</span></a></div></div></div><div class="comments formatted" id="comments"><div class="comments__header"><h2 class="comments__header-title"><a href="#comments" name="comments">komentar</a></h2><div class="comments__read-before"><span class="comments__read-before-link">baca ini sebelum berkomentar…</span><div class="comments__read-before-popup"><div class="comments__read-before-popup-i"><ul><li>Jika Anda memiliki saran apa yang harus ditingkatkan - silakan kunjungi <a href="https://github.com/javascript-tutorial/en.javascript.info/issues/new">kirimkan Github issue</a> atau pull request sebagai gantinya berkomentar.</li><li>Jika Anda tidak dapat memahami sesuatu dalam artikel – harap jelaskan.</li><li>Untuk menyisipkan beberapa kata kode, gunakan tag <code>&lt;code&gt;</code>, untuk beberapa baris – bungkus dengan tag <code>&lt;pre&gt;</code>, untuk lebih dari 10 baris – gunakan sandbox (<a href='https://plnkr.co/edit/?p=preview'>plnkr</a>, <a href='https://jsbin.com'>jsbin</a>, < a href='http://codepen.io'>codepen</a>…)</li></ul></div></div></div></div><div id="disqus_thread"></div><script>var disqus_config = function() { if (!this.page) this.page = {}; Object.assign(this.page, {"url":"https:\/\/id.javascript.info\/eval","identifier":"\/eval"}); };</script><script>var disqus_shortname = "id-javascript-info";</script><script>var disqus_enabled = true;</script></div></script></main></div><div class="sidebar page__sidebar sidebar sidebar_sticky-footer"><button class="sidebar__toggle" data-sidebar-toggle></button><a class="map" href="/tutorial/map" data-action="tutorial-map" data-tooltip="Peta tutorial"></a><div class="sidebar__inner"><div class="sidebar__content"><div class="sidebar__section"><h4 class="sidebar__section-title">Bab</h4><nav class="sidebar__navigation"><ul class="sidebar__navigation-links"><li class="sidebar__navigation-link"><a class="sidebar__link" href="/js-misc">Miscellaneous</a></li></ul></nav></div><div class="sidebar__section"><h4 class="sidebar__section-title">Navigasi pelajaran</h4><nav class="sidebar__navigation"><ul class="sidebar__navigation-links"><li class="sidebar__navigation-link"><a class="sidebar__link" href="#menggunakan-eval">Menggunakan “eval”</a></li><li class="sidebar__navigation-link"><a class="sidebar__link" href="#ringkasan">Ringkasan</a></li></ul></nav></div><div class="sidebar__section"><nav class="sidebar__navigation"><ul class="sidebar__navigation-links"><li class="sidebar__navigation-link"><a class="sidebar__link" href="#tasks">Tugas (1)</a></li><li class="sidebar__navigation-link"><a class="sidebar__link" href="#comments">komentar</a></li></ul></nav></div><div class="sidebar__section"><div class="sidebar__section-title">Bagikan</div><a class="share share_tw sidebar__share" href="https://twitter.com/share?url=https%3A%2F%2Fid.javascript.info%2Feval" rel="nofollow"></a><a class="share share_fb sidebar__share" href="https://www.facebook.com/sharer/sharer.php?s=100&amp;p[url]=https%3A%2F%2Fid.javascript.info%2Feval" rel="nofollow"></a></div><div class="sidebar__section"><a class="sidebar__link" href="https://github.com/javascript-tutorial/id.javascript.info/blob/master/1-js/99-js-misc/02-eval" rel="nofollow">Sunting di GitHub</a></div></div></div></div></div></div><div class="page-footer"><ul class="page-footer__list"><li class="page-footer__item page-footer__item_copy">©&nbsp;2007—2025&nbsp; Ilya Kantor</li><li class="page-footer__item page-footer__item_about"><a class="page-footer__link" href="/about">terkait proyek</a></li><li class="page-footer__item page-footer__item_contact"><a class="page-footer__link" href="/about#contact-us">hubungi kami</a></li></ul></div></body></html>

Pages: 1 2 3 4 5 6 7 8 9 10